Completed
Push — master ( 2e9081...e50404 )
by Alexpts
01:22
created

DeepArray::setAttr()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 9
cts 9
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 3
nop 3
crap 4
1
<?php
2
declare(strict_types = 1);
3
4
namespace PTS\Tools;
5
6
class DeepArray
7
{
8
    /** @var bool */
9
    protected $trim = false;
10
11
    /**
12
     * @param bool $trim
13
     * @return $this
14
     */
15 2
    public function setTrim(bool $trim = false): self
16
    {
17 2
        $this->trim = $trim;
18 2
        return $this;
19
    }
20
21 1
    public function getTrim(): bool
22
    {
23 1
        return $this->trim;
24
    }
25
26
    /**
27
     * @param array $name
28
     * @param array $context
29
     * @param mixed $defaultValue
30
     *
31
     * @return mixed
32
     */
33 6
    public function getAttr(array $name, array &$context, $defaultValue = false)
34
    {
35 6
        $current = array_shift($name);
36
37 6
        if (!array_key_exists($current, $context)) {
38 1
            return $defaultValue;
39
        }
40
41 6
        return count($name)
42 5
            ? $this->getAttr($name, $context[$current], $defaultValue)
43 6
            : $context[$current];
44
    }
45
46
    /**
47
     * @param array $name
48
     * @param array $context
49
     * @param mixed $value
50
     *
51
     * @return $this
52
     */
53 5
    public function setAttr(array $name, array &$context, $value): self
54
    {
55 5
        $current = array_shift($name);
56
57 5
        if (count($name) === 0) {
58 5
            $this->setValueToContext($current, $context, $value);
59 5
            return $this;
60
        }
61
62 3
        if (!array_key_exists($current, $context) || !is_array($context[$current])) {
63 2
            $context[$current] = [];
64
        }
65
66 3
        $this->setAttr($name, $context[$current], $value);
67
68 3
        return $this;
69
    }
70
71 5
    protected function setValueToContext(string $name, array &$context, $value): void
72
    {
73 5
        $context[$name] = $value;
74
75 5
        if ($value === null && $this->trim) {
76 1
            unset($context[$name]);
77
        }
78 5
    }
79
}
80