Skip to content

[ObjectMapper] Enum mapping process #61044

@Nayte91

Description

@Nayte91

Description

Hello,

Sometimes you have to map around Enums:

  1. Sometimes both have the same enum,
  2. Sometimes one object has enum, and the other one has string, or int,
  3. Sometimes both have different enum (??)

for 1, I need to test but I think it's directly done,
for 2, there is 2 ways from enum to scalar, and from scalar to enum:

  • From enum to scalar: try to give the 'value' if exists, otherwise try to give the 'name',
  • From scalar to enum: from() or tryFrom()?

For 3, as I smell it to be far for best practices, I don't know if we want the process to go smoothly (enum is converted to scalar with its 'value', then when the other object catch it, it goes with a tryFrom() and we don't care if it worked or not), or blow away just for trying?

Sorry if I write a feature already existing, but I dug into doc and code and didn't found anything around this.

Good day!

Example

I made some tests:
I got an Organization Entity, let's say with a public ?int $id, and a public ?Nature $nature.
Nature is a stringed enum with cases like club, team, ..
Also have a SaveOrganization Command class #[AsMessage] that will be handled.
I will use the ObjectMapper to go from Command to Entity.

  1. If Command and Entity both have $nature property typed with Nature: mapping is OK.
  2. if Command has an OrganizationNature typed $nature, and Entity has a string one: I don't find any simple way to achieve that, beside creating a callable class or a TransformCallableInterface one.
  3. if Command has a string typed $nature, and Entity has a Nature one: same, I don't find any way, as #[Map(transform: [Nature::class, 'tryFrom'])] doesn't seem to fit on a property.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions