Skip to content

[Proposal]: Adjust handling of EnumEntry::toString() for backed enums #2107

Open

Description

@stloyd

Describe the Proposal

Right now, EnumEntry::toString() calls will always return a name for any given enum, while it's most of the time a perfect fit, but when you have \BackedEnum, you may expect to get the value aligned to the name, not the name itself.

API Adjustments

    public function toString() : string
    {
        if ($this->value === null) {
            return '';
        }

        // New code
        if ($this->value instanceof \BackedEnum) {
            return (string) $this->value->value;
        }

        return $this->value->name;
    }

Are you intending to also work on proposed change?

Yes

Are you interested in sponsoring this change?

None

Integration & Dependencies

No response

Activity

  1. norberttech commented on Dec 28, 2025

    @norberttech
    Member

    oh I see what you mean, hmm lets take one step back and maybe think about purpose of toString() method.

    Right now, method toString() is being used in different contexts:

    • by EntryNormalizers (which I guess took you here)
    • by printers, like to_output()

    plus some minor places like Row::hash()

    But you are right, with BackedEnum it might make sense in certain places to use value, instead of name. However I believe current approach is correct one.
    Let me explain, why:

    <?php
    
    enum Color: int
    {
        case Red = 0;
        case Orange = 1;
        case Yellow = 2;
        case Green = 3;
        case Blue = 4;
        case Indigo = 5;
        case Violet = 6;
        case Purple = 7;
        case Pink = 8;
        case Brown = 9;
        case Gray = 10;
    }

    So if we print values from toString() method we are pretty much getting in console under column name color just integers when we use to_output().

    I think that EntryNormalizers should use EnumEntry::value() : ?\UnitEnum and be configurable, which means there should be a possibility to configure entry normalizer to:

    • always use name for all entries
    • always use value for all entries
    • use name for only specific entries
    • use value for only specific entries
    • by default always use name

    This would need to be a similar configuration to date/time/datetime formats that we pass to normalizers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions