Skip to content

Instantly share code, notes, and snippets.

@devhammed
Last active February 6, 2024 11:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devhammed/5a90f0a6f0fea6606e1dc7ea365c8ace to your computer and use it in GitHub Desktop.
Save devhammed/5a90f0a6f0fea6606e1dc7ea365c8ace to your computer and use it in GitHub Desktop.
This is a Livewire 3 Synthesizer (https://livewire.laravel.com/docs/synthesizers) for classes using spatie/laravel-data package (https://spatie.be/docs/laravel-data/v3/introduction)!
<?php
namespace App\Support\Synthesizers;
use Spatie\LaravelData\Data;
use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth;
class SpatieLaravelDataSynthesizer extends Synth
{
public static string $key = 'spld';
public static function match(mixed $target): bool
{
return $target instanceof Data;
}
public function dehydrate(Data $target): array
{
return [
$target->toArray(),
['class' => get_class($target)],
];
}
public function hydrate(?array $value, array $meta): ?Data
{
if (is_null($value)) {
return null;
}
$class = $meta['class'];
if ( ! is_subclass_of($class, Data::class)) {
return null;
}
return $class::from($value);
}
public function set(Data $target, string $key, mixed $value): void
{
$target->{$key} = $value;
}
public function unset(Data $target, string $key): void
{
unset($target->{$key});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment