-
Notifications
You must be signed in to change notification settings - Fork 1
/
DataAccessor.php
78 lines (63 loc) · 2.2 KB
/
DataAccessor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
declare(strict_types=1);
namespace Spiral\Livewire\Component;
use Adbar\Dot;
use Spiral\Attributes\ReaderInterface;
use Spiral\Livewire\Attribute\Model;
use Spiral\Marshaller\MarshallerInterface;
use Symfony\Component\PropertyAccess\PropertyPath;
final class DataAccessor implements DataAccessorInterface
{
public function __construct(
private readonly MarshallerInterface $marshaller,
private readonly ReaderInterface $reader
) {
}
public function getData(LivewireComponent $component): array
{
$models = [];
foreach ((new \ReflectionClass($component))->getProperties() as $property) {
if (null !== $this->reader->firstPropertyMetadata($property, Model::class)) {
$models[] = $property->getName();
}
}
/** @var array $data */
$data = \array_filter(
$this->marshaller->marshal($component),
static fn (string $key) => \in_array($key, $models, true),
\ARRAY_FILTER_USE_KEY
);
return $data;
}
/**
* @param non-empty-string $propertyPath
*/
public function setValue(LivewireComponent $component, string $propertyPath, mixed $value): void
{
$data = new Dot($this->getData($component));
$data->set($propertyPath, $value);
$this->marshaller->unmarshal($data->all(), $component);
}
/**
* @param non-empty-string $propertyPath
*/
public function getValue(LivewireComponent $component, string $propertyPath, mixed $default = null): mixed
{
$data = new Dot($this->getData($component));
return $data->get($propertyPath, $default);
}
/**
* @param non-empty-string $propertyPath
*/
public function hasModel(LivewireComponent $component, string $propertyPath): bool
{
$path = new PropertyPath($propertyPath);
foreach ((new \ReflectionClass($component))->getProperties() as $reflection) {
$model = $this->reader->firstPropertyMetadata($reflection, Model::class);
if ((null !== $model) && $path->getElement(0) === $reflection->getName()) {
return true;
}
}
return false;
}
}