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
|
|
|
|