Registry::set()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
crap 2
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