1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Shlinkio\Shlink\Config\Collection; |
6
|
|
|
|
7
|
|
|
use function array_key_exists; |
8
|
|
|
use function array_shift; |
9
|
|
|
use function count; |
10
|
|
|
use function is_array; |
11
|
|
|
|
12
|
|
|
final class PathCollection |
13
|
|
|
{ |
14
|
|
|
private array $array; |
15
|
|
|
|
16
|
16 |
|
public function __construct(array $array = []) |
17
|
|
|
{ |
18
|
16 |
|
$this->array = $array; |
19
|
|
|
} |
20
|
|
|
|
21
|
8 |
|
public function pathExists(array $path): bool |
22
|
|
|
{ |
23
|
8 |
|
return $this->checkPathExists($path, $this->array); |
24
|
|
|
} |
25
|
|
|
|
26
|
8 |
|
private function checkPathExists(array $path, array $array): bool |
27
|
|
|
{ |
28
|
|
|
// As soon as a step is not found, the path does not exist |
29
|
8 |
|
$step = array_shift($path); |
30
|
8 |
|
if (! array_key_exists($step, $array)) { |
31
|
3 |
|
return false; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
// Once the path is empty, we have found all the parts in the path |
35
|
6 |
|
if (empty($path)) { |
36
|
4 |
|
return true; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
// If current value is not an array, then we have not found the path |
40
|
4 |
|
$newArray = $array[$step]; |
41
|
4 |
|
if (! is_array($newArray)) { |
42
|
1 |
|
return false; |
43
|
|
|
} |
44
|
|
|
|
45
|
4 |
|
return $this->checkPathExists($path, $newArray); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @return mixed |
50
|
|
|
*/ |
51
|
8 |
|
public function getValueInPath(array $path) |
52
|
|
|
{ |
53
|
8 |
|
$array = $this->array; |
54
|
|
|
|
55
|
|
|
do { |
56
|
8 |
|
$step = array_shift($path); |
57
|
8 |
|
if (! is_array($array) || ! array_key_exists($step, $array)) { |
58
|
4 |
|
return null; |
59
|
|
|
} |
60
|
|
|
|
61
|
6 |
|
$array = $array[$step]; |
62
|
6 |
|
} while (! empty($path)); |
63
|
|
|
|
64
|
4 |
|
return $array; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param mixed $value |
69
|
|
|
*/ |
70
|
|
|
public function setValueInPath($value, array $path): void |
71
|
|
|
{ |
72
|
|
|
$ref =& $this->array; |
73
|
|
|
|
74
|
|
|
while (count($path) > 1) { |
75
|
|
|
$currentKey = array_shift($path); |
76
|
|
|
if (! array_key_exists($currentKey, $ref)) { |
77
|
|
|
$ref[$currentKey] = []; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
$ref =& $ref[$currentKey]; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
$ref[array_shift($path)] = $value; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
public function toArray(): array |
87
|
|
|
{ |
88
|
|
|
return $this->array; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|