Passed
Push — master ( 7ef18e...f705ba )
by Misha
45s
created

DataRetriever::getByPath()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 3
dl 0
loc 17
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Communibase\DataBag;
6
7
final class DataRetriever
8
{
9
    /**
10
     * @param array<string,array> $data
11
     * @param mixed $default
12
     *
13
     * @return mixed
14
     */
15
    public function getByPath(array $data, string $path, $default = null)
16
    {
17
        [$entityType, $path] = explode('.', $path, 2);
18
19
        // Direct property
20
        if (strpos($path, '.') === false) {
21
            return $data[$entityType][$path] ?? $default;
22
        }
23
24
        // Indexed
25
        [$property, $index] = explode('.', $path, 2);
26
27
        if (empty($data[$entityType][$property])) {
28
            return $default;
29
        }
30
31
        return $this->getIndexedValue((array)$data[$entityType][$property], $index, $default);
32
    }
33
34
    /**
35
     * @param array<string,array> $properties
36
     * @param mixed $default
37
     *
38
     * @return mixed
39
     */
40
    private function getIndexedValue(array $properties, string $index, $default)
41
    {
42
        $targetProperty = null;
43
        if (strpos($index, '.') > 0) {
44
            [$index, $targetProperty] = explode('.', $index, 2);
45
        }
46
47
        $translatedIndex = $index;
48
49
        if (!is_numeric($index)) {
50
            $translatedIndex = null;
51
            foreach ($properties as $nodeIndex => $node) {
52
                if (isset($node['type']) && $node['type'] === $index) {
53
                    $translatedIndex = $nodeIndex;
54
                    break;
55
                }
56
            }
57
        }
58
59
        if ($translatedIndex === null) {
60
            return $default;
61
        }
62
63
        if ($targetProperty === null) {
64
            return $properties[$translatedIndex] ?? $default;
65
        }
66
67
        return $properties[$translatedIndex][$targetProperty] ?? $default;
68
    }
69
}
70