Dynamic casting based on passed data #102
-
Hi, thank you for such a nice package! I need to pass data from Data Object into my Custom Cast:
class RealEstateData extends Data
{
public function __construct(
#[WithCast(RealEstateTypeCast::class)]
public readonly ?RealEstateTypeEnum $type,
#[WithCast(RealEstatePropertiesCast::class, type: $this->type)] // I know this is not allowed
public ?object $client_properties,
) {
}
}
enum RealEstateTypeEnum: string
{
case House = 'house';
case Apartment = 'apartment';
} Then in my class RealEstatePropertiesCast implements Cast
{
public function __construct(
protected RealEstateTypeEnum $type,
) {
}
public function cast(DataProperty $property, mixed $value): mixed
{
return match ($this->type) {
RealEstateTypeEnum::House => RealEstateHousePropertiesData::from($value),
RealEstateTypeEnum::Apartment => RealEstateApartmentPropertiesData::from($value),
default => throw CannotCastRealEstateProperties::create($this->type->name, $value),
};
}
} The biggest issue is that somehow I am not able to pass enum type of current instance of data object into my cast in a "clean way". Thanks for any suggestions. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hi @davidkvasnovsky, At the moment we do not have such a feature, adding it to the |
Beta Was this translation helpful? Give feedback.
-
You could skip the cast and use a magical creation method(https://spatie.be/docs/laravel-data/v1/as-a-data-transfer-object/creating-a-data-object#magical-creation), you have access to all the values being passed over there. I think that's the only solution, for now. |
Beta Was this translation helpful? Give feedback.
You could skip the cast and use a magical creation method(https://spatie.be/docs/laravel-data/v1/as-a-data-transfer-object/creating-a-data-object#magical-creation), you have access to all the values being passed over there. I think that's the only solution, for now.