Custom value casters?
davidmondok opened this issue · comments
David Mondok commented
I've tried answering the question myself by digging deep into the documentation and code itself but wasn't able to.
Basically I'm looking for a way to create custom source data casters similar to how callable tranformers work. I hope the example below makes my intentions clear.
namespace My\App;
final class IdCast
{
public function cast(mixed $value): ?int
{
if (is_object($value) && isset($value->ID)) {
return (int)$value->ID;
}
if (is_numeric($value) && (int)$value !== 0) {
return (int)$value;
}
return null;
}
}
final class Data {
public function __construct(
#[\My\App\IdCast]
public readonly ?int $id,
) {
}
}
// $dataOne->id === 1
$dataOne = (new \CuyZ\Valinor\MapperBuilder())
->mapper()
->map(Data::class, [
'id' => new class(1) { public function __construct(public int $id) {} },
]);
// $dataTwo->id === 2
$dataTwo = (new \CuyZ\Valinor\MapperBuilder())
->mapper()
->map(Data::class, [
'id' => 2
]);