Skip to content

Use const of enum as scalar value to map #811

@rubenrubiob

Description

@rubenrubiob

Hello,

Suppose we have this enum, that contains some constants within it:

enum DummyEnum: string
{
    case A = 'A';
    case B = 'B';

    public const string ELEMENT_X = 'X';
    public const string ELEMENT_Z = 'Z';
}

And that we have a DTO with a scalar value in which we want to have a value of ELEMENT_*:

final readonly class DummyDTO
{
    public function __construct(
        /** @var DummyEnum::ELEMENT_* */
        public string $element,
    ) {}
}

If we try to map that DummyDTO using Valinor:

new MapperBuilder()
    ->mapper()
    ->map(
        DummyDTO::class,
        ['element' => 'Z']
    );

We get this error:

Error while trying to map to `DummyDTO`: the type `DummyEnum::ELEMENT_*` for parameter `DummyDTO::__construct($element)` could not be resolved: cannot find enum case with pattern `DummyEnum::ELEMENT_*`.

It seems the library detects that the class is an enum, so it tries to map it using the enum cases.

If, instead, we use a class to reference the constants within it, as stated in the docs, it works fine:

final readonly class DummyClass
{
    public const string ELEMENT_X = 'X';
    public const string ELEMENT_Z = 'Z';
}

final readonly class DummyDTO
{
    public function __construct(
        /** @var DummyClass::ELEMENT_* */
        public string $element,
    ) {}
}

new MapperBuilder()
    ->mapper()
    ->map(
        DummyDTO::class,
        ['element' => 'Z']
    );

So, should we be able to map using the constants in an enum? Or that is a case that should not be possible?

Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions