1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Lneicelis\Transformer\Pipe; |
4
|
|
|
|
5
|
|
|
use Lneicelis\Transformer\Contract\CanPipe; |
6
|
|
|
use Lneicelis\Transformer\Contract\HasLazyProperties; |
7
|
|
|
use Lneicelis\Transformer\Contract\HasSchema; |
8
|
|
|
use Lneicelis\Transformer\LoaderRegistry; |
9
|
|
|
use Lneicelis\Transformer\ValueObject\Context; |
10
|
|
|
use Lneicelis\Transformer\ValueObject\Deferred; |
11
|
|
|
use Lneicelis\Transformer\ValueObject\Path; |
12
|
|
|
|
13
|
|
|
class LoaderPropertiesPipe implements CanPipe |
14
|
|
|
{ |
15
|
|
|
/** @var LoaderRegistry */ |
16
|
|
|
protected $loaderRegistry; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param LoaderRegistry $loaderRegistry |
20
|
|
|
*/ |
21
|
|
|
public function __construct(LoaderRegistry $loaderRegistry) |
22
|
|
|
{ |
23
|
|
|
$this->loaderRegistry = $loaderRegistry; |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param object $resource |
28
|
|
|
* @param Context $context |
29
|
|
|
* @param Path $path |
30
|
|
|
* @param $data |
31
|
|
|
* @return array |
32
|
|
|
*/ |
33
|
|
|
public function pipe($resource, Context $context, Path $path, $data) |
34
|
|
|
{ |
35
|
|
|
if (! $context instanceof HasSchema) { |
|
|
|
|
36
|
|
|
return $data; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
$loadableProperties = $this->loaderRegistry->getLoadableProperties(get_class($resource)); |
40
|
|
|
$schema = $this->getPathSchema($path, $context->getSchema()); |
41
|
|
|
$schemaProperties = $this->getProperties($schema); |
42
|
|
|
$properties = array_intersect($schemaProperties, $loadableProperties); |
43
|
|
|
|
44
|
|
|
foreach ($properties as $property) { |
45
|
|
|
$data[$property] = new Deferred($resource, $property); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return $data; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
private function getProperties(array $schema): array |
52
|
|
|
{ |
53
|
|
|
return array_map(function ($value, $key) { |
54
|
|
|
return is_string($value) ? $value : $key; |
55
|
|
|
}, $schema, array_keys($schema)); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
private function getPathSchema(Path $path, array $schema): array |
59
|
|
|
{ |
60
|
|
|
$segments = array_filter($path->getSegments(), function ($segment) { |
61
|
|
|
return ! is_numeric($segment); |
62
|
|
|
}); |
63
|
|
|
|
64
|
|
|
return $this->arrayGet($schema, $segments, []); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
private function arrayGet(array $array, array $path, $default): array |
68
|
|
|
{ |
69
|
|
|
foreach ($path as $key) { |
70
|
|
|
if (! array_key_exists($key, $array)) { |
71
|
|
|
return $default; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
$array = $array[$key]; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return $array; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|