Issues (3)

src/Pipe/LoaderPropertiesPipe.php (1 issue)

Severity
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 2
    public function __construct(LoaderRegistry $loaderRegistry)
22
    {
23 2
        $this->loaderRegistry = $loaderRegistry;
24 2
    }
25
26
    /**
27
     * @param object $resource
28
     * @param Context $context
29
     * @param Path $path
30
     * @param $data
31
     * @return array
32
     */
33 2
    public function pipe($resource, Context $context, Path $path, $data)
34
    {
35 2
        if (! $context instanceof HasSchema) {
0 ignored issues
show
$context is always a sub-type of Lneicelis\Transformer\Contract\HasSchema.
Loading history...
36
            return $data;
37
        }
38
39 2
        $loadableProperties = $this->loaderRegistry->getLoadableProperties(get_class($resource));
40 2
        $schema = $this->getPathSchema($path, $context->getSchema());
41 2
        $schemaProperties = $this->getProperties($schema);
42 2
        $properties = array_intersect($schemaProperties, $loadableProperties);
43
44 2
        foreach ($properties as $property) {
45 2
            $data[$property] = new Deferred($resource, $property);
46
        }
47
48 2
        return $data;
49
    }
50
51
    private function getProperties(array $schema): array
52
    {
53 2
        return array_map(function ($value, $key) {
54 2
            return is_string($value) ? $value : $key;
55 2
        }, $schema, array_keys($schema));
56
    }
57
58
    private function getPathSchema(Path $path, array $schema): array
59
    {
60 2
        $segments = array_filter($path->getSegments(), function ($segment) {
61 2
            return ! is_numeric($segment);
62 2
        });
63
64 2
        return $this->arrayGet($schema, $segments, []);
65
    }
66
67 2
    private function arrayGet(array $array, array $path, $default): array
68
    {
69 2
        foreach ($path as $key) {
70 1
            if (! array_key_exists($key, $array)) {
71
                return $default;
72
            }
73
74 1
            $array = $array[$key];
75
        }
76
77 2
        return $array;
78
    }
79
}
80