Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom value casters? #538

Open
davidmondok opened this issue May 6, 2024 · 0 comments
Open

Custom value casters? #538

davidmondok opened this issue May 6, 2024 · 0 comments

Comments

@davidmondok
Copy link

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
    ]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant