eloquent / enumeration

An enumeration implementation for PHP.
MIT License
147 stars 8 forks source link

__set_state problems made by var_export #25

Closed sazo closed 5 years ago

sazo commented 6 years ago

Hallo,

We are facing a problem with var_export and enumeration. More concrete laravel is making a config cache with var_export for speed optimization.

Problem:

return var_export(\Enum\QueueStatus::DONE(), true);

returns

Enum\QueueStatus::__set_state(array( 'value' => 0, 'key' => 'DONE', ))

and generates

No member with key equal to '__set_state' defined in class 'Enum\QueueStatus'

Is their a nice workaround for this or is a fix in the package required?

Thx for a nice package.

ezzatron commented 6 years ago

It's a similar challenge to serialization. If you have a read through the discussion in #23 you'll probably get a better idea of the problem.

Basically, this library relies heavily on the fact that only a single instance of each enum member exists, so that === can be used to compare instances. If instances of an enum class are created by some other means, like unserialization, or executing the output from var_export, it breaks that guarantee.

I would suggest, that if it's possible, you keep either the key (QueueStatus::DONE()->key()) or the value (QueueStatus::DONE()->value()) in your config, and convert that back into the actual enum member later via either QueueStatus::memberByKey($key) or QueueStatus::memberByValue($value).