Skip to content

Commit

Permalink
Merge pull request #591 from edalzell/feature/data-collection-synth
Browse files Browse the repository at this point in the history
Add DataCollectionSynth
  • Loading branch information
rubenvanassche authored Mar 1, 2024
2 parents 121c708 + d0296a2 commit 3efe949
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions src/Synths/DataCollectionSynth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

namespace Spatie\LaravelData\Synths;

use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth;
use Spatie\LaravelData\DataCollection;

class DataCollectionSynth extends Synth
{
public static $key = 'dtcl';

public static function match($target)
{
return get_class($target) == DataCollection::class;
}

public function dehydrate(DataCollection $target, $dehydrateChild)
{
$data = $target->all();

foreach ($data as $key => $child) {
$data[$key] = $dehydrateChild($key, $child);
}

return [
$data,
['class' => get_class($target)],
];
}

/**
* @param array<mixed> $value
* @param array<string, class-string> $meta
* @param mixed $hydrateChild
* @return \Spatie\LaravelData\DataCollection
*/
public function hydrate($value, $meta, $hydrateChild)
{
foreach ($value as $key => $child) {
$value[$key] = $hydrateChild($key, $child);
}

return $meta['class']::make($value);
}

public function get(&$target, $key)
{
return $target[$key] ?? null;
}

public function set(&$target, $key, $value)
{
$target[$key] = $value;
}
}

0 comments on commit 3efe949

Please sign in to comment.