Skip to content

Conversation

@frostieDE
Copy link
Contributor

Enables values casting

@magnusnordlander
Copy link
Member

Thanks for this PR! This seems like a useful feature, I would however prefer for there to be an interface that enum classes can implement and checking for that instead of using method_exists.

@frostieDE
Copy link
Contributor Author

In general, I agree with your proposal. But here is the thing: In case of convertToPHPValue I do not have an instance of the target enum class, thus I cannot check whether it implements any interface (at least not using instanceof). The only way to check whether the enum implements the needed interface, I have to use reflection.

So: do you thing it is worth implementing?

@frostieDE
Copy link
Contributor Author

frostieDE commented Nov 23, 2019

When thinking about it, I am not sure whether such functionality should be implemented in the enum itself. What I actually want to do with both methods is converting the value.

Maybe we can leverage a custom annotation and seperate converter classes:

interface EnumConverterInterface {

    /**
     * @param string $value
     * @return mixed
     */
    public function castValueIn($value);

    /**
     * @param mixed $value
     * @return string
     */
    public function castValueOut($value);
}
class IntegerEnumValuesConverter implements EnumConverterInterface {

    public function castValueIn($value) {
        return (int)$value;
    }

    public function castValueOut($value) {
        return (string)$value;
    }
}
use MyCLabs\Enum\Enum;

/**
 * @EnumConverter(converterClass="IntegerEnumValuesConverter")
 * @method static StudyGroupType Grade()
 * @method static StudyGroupType Course()
 */
class StudyGroupType extends Enum {
    private const Grade = 1;
    private const Course = 2;
}

The code would be a bit more complicated than before, but I guess it would be more flexible?

Downside of this approach: we cannot inject the AnnotationReader which is created by Symfony thus we cannot use any caching functionalities...

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants