CuyZ / Valinor

PHP library that helps to map any input into a strongly-typed value object structure.

Home Page:https://valinor.cuyz.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Custom value casters?

davidmondok opened this issue · comments

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
    ]);