ObjectHydrator icon indicating copy to clipboard operation
ObjectHydrator copied to clipboard

Expose PropertyHydrationDefinition to PropertyCaster::cast() to access inferred type

Open JRoblesAtQuadrant opened this issue 1 year ago • 1 comments

I've got a model, that uses several VO properties, using a ValueObjectInterface.

Trying to create a generic PropertyCaster, CastToValueObjectInterface, I miss the concrete Attribute target (the property on whom is applied) to hydrate the property without need to explicity add the class to be hydrated on the attribute


class Name implements ValueObject {
     public function from(mixed $value): self
}

final readonly class Model {
    #[CastAsValueObject]
    public Name $name
}

readonly class CastToValueObjectInterface implements PropertyCaster {
    public function cast(mixed $value, ObjectMapper $hydrator, PropertyHydrationDefinition $context=null): mixed
    {
        if (!$context?->firstTypeName instanceOf ValueObject)
            throw \InvalidArgumentException("Annotated property does not implement ValueObject");
            
       return ($context->firstTypeName)::from($value);
    }
}


JRoblesAtQuadrant avatar Apr 26 '24 09:04 JRoblesAtQuadrant

I'd go so far as to suggest the Caster shouldn't be necessary. The Hydrator should just figure out it's a value object (contructor with single parameter?) and create it.

cooperaj avatar May 30 '25 13:05 cooperaj