Added new named constructor to create enum from mixed#135
Added new named constructor to create enum from mixed#135mnapoli merged 1 commit intomyclabs:masterfrom
Conversation
d33c58e to
9343c3f
Compare
9343c3f to
5cdc5da
Compare
The current implementation of Enum requires to pass a valid enum value to class constructor. With this new named constructor we can just pass any value to enum and get an instance or unexpected value exception.
5cdc5da to
bd92d06
Compare
mnapoli
left a comment
There was a problem hiding this comment.
Very good! I wasn't so keen on adding yet new methods, but this makes sense and will make this library closer to the future PHP 8.1 enums!
Thanks!
| * @psalm-pure | ||
| * @psalm-assert T $value | ||
| */ | ||
| public static function assertValidValue($value): void |
There was a problem hiding this comment.
I propose to not extend the API also with this static method and have it private.
I wanted to change how it behaves here: #136 (comment)
There was a problem hiding this comment.
I understand what you say. Yes, it can be useful as a public API as well to just validate without creating the instances.
It would have help a bit in making sure is_array or array_search are not called in constructor more than once when object is created,
is_array is already called twice when from() is used and I was thinking that should also be optimized.
There was a problem hiding this comment.
And this endpoint can be made completely independent from the ctor in the patch doing the perf optimization, no?
…ound to any template These functions had a `T` template parameter in them, but this `T` is completely decoupled from the one defined at class-level (and therefore at `Enum` instance level, rather than statically): * `Enum::from()` * `Enum::isValid()` * `Enum::assertValidValue()` * `Enum::assertValidValueReturningKey()` (internal detail) In practice, this means that myclabs#135 (Added new named constructor to create enum from mixed) was not a valid approach to infer types for enumerable values, when performed statically. A new approach will be attempted, but the current one will likely need to be scrapped for now. In practice, `@psalm-assert`, `@psalm-assert-if-true` and `@psalm-return static<T>` had no effect on these methods, due to a design-level issue that wasn't spotted (by myself either) at review.
The current implementation of Enum requires to pass a valid enum value to class constructor. With this new named constructor we can just pass any value to enum and get an instance or unexpected value exception. In the end it's like the class constructor except for it makes psalm happy.