-
Notifications
You must be signed in to change notification settings - Fork 0
/
DotNotationCollection.php
114 lines (101 loc) · 2.69 KB
/
DotNotationCollection.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
declare(strict_types=1);
namespace Peak\Collection;
use Peak\Blueprint\Collection\Dictionary;
use \RuntimeException;
use function array_key_exists;
use function array_shift;
use function count;
use function explode;
use function is_array;
class DotNotationCollection extends Collection implements Dictionary
{
/**
* @const string
*/
const SEPARATOR = '.';
/**
* Return a path value
* @param string $path
* @param mixed $default
* @return mixed
*/
public function get(string $path, $default = null)
{
$array = $this->items;
if (!empty($path)) {
$keys = $this->explode($path);
foreach ($keys as $key) {
if (!is_array($array) || !array_key_exists($key, $array)) {
return $default;
}
$array = $array[$key];
}
}
return $array;
}
/**
* Add a path
* @param string $path
* @param mixed $value
*/
public function set(string $path, $value): void
{
if (!empty($path)) {
$at = & $this->items;
$keys = $this->explode($path);
while (count($keys) > 0) {
if (count($keys) === 1) {
if (!is_array($at)) {
throw new RuntimeException('Can not set value at this path ['.$path.'] because is not array.');
}
$at[array_shift($keys)] = $value;
} else {
$key = array_shift($keys);
if (!isset($at[$key])) {
$at[$key] = [];
}
$at =& $at[$key];
}
}
} else {
$this->items = [$value];
}
}
/**
* Merge a path with an array
* @param string $path
* @param array $values
*/
public function add(string $path, array $values): void
{
$get = (array)$this->get($path);
$this->set($path, $this->arrayMergeRecursiveDistinct($get, $values));
}
/**
* Check if we have path
* @param string $path
* @return bool
*/
public function has(string $path): bool
{
$keys = $this->explode($path);
$array = $this->items;
foreach ($keys as $key) {
if (!is_array($array) || !array_key_exists($key, $array)) {
return false;
}
$array = $array[$key];
}
return true;
}
/**
* Explode path string
* @param string $path
* @return mixed
*/
protected function explode(string $path)
{
return explode(self::SEPARATOR, $path);
}
}