nelmio / alice

Expressive fixtures generator
MIT License
2.49k stars 330 forks source link

Support for enums #1143

Closed edhgoose closed 11 months ago

edhgoose commented 11 months ago

We're using enum's in the constructor of an object.

Something like:

new Object(Enum::X)

From my research, I can't see a way to do this in the yml config.

In the meantime, I've used a custom instantiator for this case, but I'm wondering if there's a way this could be supported and/or if there's documentation on how to do this?

Thanks!

theofidry commented 11 months ago

Hi!

I honestly have no idea. I guess a solution would to allow to set a backed enum value or the enum name and then the instantiator can take care of casting it to an enum?

edhgoose commented 11 months ago

This sounds sensible. I'm not familiar with the codebase, but how does it work for Constants? Could something similar to that be used?

theofidry commented 11 months ago

Honestly I don't remember how it's done with constants either. I think the best starting point is to write a test doing what you want: https://github.com/nelmio/alice/blob/master/tests/Loader/LoaderIntegrationTest.php#L4073

And from where work out what's missing. IIRC there is two processes: building the fixture which is an abstract representation of the object to build, and then actually creating them. It's probably going to be something about a value resolver https://github.com/nelmio/alice/blob/master/src/Generator/Resolver/Value/ChainableValueResolverInterface.php I guess. But it's also been quite long for me so I can't say for certain

edhgoose commented 11 months ago

Turned out it's already supported and works fine:

My\Class:
    name:
        __construct:
            [
                "some-string",
                <(My\Class\Constants\Enum::X)>,
            ]

Thanks for your help @theofidry - you pointed me in the right direction. It's these lines that do it: https://github.com/nelmio/alice/blob/b9bb1cbe3bbb0e43ae88f739ebfa86e06ad1a169/src/Generator/Resolver/Value/Chainable/EvaluatedValueResolver.php#L65-L75