1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Nayjest\Collection\Extended; |
4
|
|
|
|
5
|
|
|
use Evenement\EventEmitterTrait; |
6
|
|
|
use Nayjest\Collection\CollectionDataTrait; |
7
|
|
|
use Nayjest\Collection\CollectionReadTrait; |
8
|
|
|
|
9
|
|
|
class Registry implements RegistryInterface |
10
|
|
|
{ |
11
|
|
|
use CollectionDataTrait; |
12
|
|
|
use CollectionReadTrait; |
13
|
|
|
use ObjectCollectionTrait; |
14
|
|
|
use EventEmitterTrait; |
15
|
|
|
|
16
|
|
|
public function __construct(array $items = []) |
17
|
|
|
{ |
18
|
|
|
$this->setMany($items); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param string $key |
23
|
|
|
* @param object $item |
24
|
|
|
* @return $this |
25
|
|
|
*/ |
26
|
|
|
public function set($key, $item) |
27
|
|
|
{ |
28
|
|
|
$this->emit('change', [$key, $item, $this]); |
29
|
|
|
$this->items()[$key] = $item; |
30
|
|
|
return $this; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param string $key |
35
|
|
|
* @return $this |
36
|
|
|
*/ |
37
|
|
|
public function removeByKey($key) |
38
|
|
|
{ |
39
|
|
|
$items = &$this->items(); |
40
|
|
|
if (array_key_exists($key, $items)) { |
41
|
|
|
$this->emit('change', [$key, null, $this]); |
42
|
|
|
unset($items[$key]); |
43
|
|
|
} |
44
|
|
|
return $this; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* @param array $items |
49
|
|
|
* @return $this |
50
|
|
|
*/ |
51
|
|
|
public function setMany(array $items) |
52
|
|
|
{ |
53
|
|
|
foreach ($items as $name => $item) { |
54
|
|
|
$this->set($name, $item); |
55
|
|
|
} |
56
|
|
|
return $this; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @param string $key |
61
|
|
|
* @return bool |
62
|
|
|
*/ |
63
|
|
|
public function hasKey($key) |
64
|
|
|
{ |
65
|
|
|
$keyExists = array_key_exists($key, $this->items()); |
66
|
|
|
return $keyExists && $this->items()[$key] !== null; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param string $key |
71
|
|
|
* @return null|object |
72
|
|
|
*/ |
73
|
|
|
public function get($key) |
74
|
|
|
{ |
75
|
|
|
return $this->hasKey($key) ? $this->items()[$key] : null; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @param callable $callback |
80
|
|
|
* @return $this |
81
|
|
|
*/ |
82
|
|
|
public function onChange(callable $callback) |
83
|
|
|
{ |
84
|
|
|
$this->on('change', $callback); |
85
|
|
|
return $this; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|