Passed
Push — master ( 65b336...1323cd )
by Бабичев
44s
created

Attachable::initializer()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Bavix\Router;
4
5
use Bavix\Exceptions\Runtime;
6
7
trait Attachable
8
{
9
10
    /**
11
     * @var string
12
     */
13
    protected $_name;
14
15
    /**
16
     * Attachable constructor.
17
     *
18
     * @param string $key
19
     * @param array $storage
20
     */
21 6
    protected function initializer(string $key, array $storage): void
22
    {
23 6
        $this->_name = $key;
24 6
        $this->attached($storage);
25 6
    }
26
27
    /**
28
     * @param array $storage
29
     * @return array
30
     */
31
    protected function filter(array $storage): array
32
    {
33 6
        return \array_filter($storage, function (string $key) {
34 6
            $this->checkProperty($key);
35 6
            return $key{0} !== '@'; // for xml
36 6
        }, \ARRAY_FILTER_USE_KEY);
37
    }
38
39
    /**
40
     * @param string $key
41
     * @throws
42
     */
43 6
    protected function checkProperty(string $key): void
44
    {
45 6
        if ($key{0} === '_' || !\property_exists($this, $key)) {
46
            throw new Runtime(\sprintf('The key `%s` is not registered', $key));
47
        }
48 6
    }
49
50
    /**
51
     * @param array $storage
52
     */
53 6
    protected function attached(array $storage): void
54
    {
55 6
        foreach ($this->filter($storage) as $key => $value) {
56 6
            $this->$key = $value;
57
        }
58 6
    }
59
60
}
61