ArrayPath::set()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 15
c 0
b 0
f 0
ccs 8
cts 8
cp 1
rs 10
cc 3
nc 3
nop 3
crap 3
1
<?php declare(strict_types=1);
2
3
namespace PeeHaa\ArrayPath;
4
5
class ArrayPath
6
{
7
    private $delimiter;
8
9 12
    public function __construct($delimiter = '.')
10
    {
11 12
        $this->delimiter = $delimiter;
12 12
    }
13
14 5
    public function get(array $source, string $path)
15
    {
16 5
        $keys = explode($this->delimiter, $path);
17
18 5
        $currentSource = $source;
19
20 5
        foreach ($keys as $key) {
21 5
            if (!array_key_exists($key, $currentSource)) {
22 2
                throw new NotFoundException();
23
            }
24
25 4
            $currentSource = $currentSource[$key];
26
        }
27
28 3
        return $currentSource;
29
    }
30
31 4
    public function set(array &$source, string $path, $value): void
32
    {
33 4
        $keys = explode($this->delimiter, $path);
34
35 4
        $currentSource = &$source;
36
37 4
        foreach ($keys as $key) {
38 4
            if (!array_key_exists($key, $currentSource)) {
39 3
                $currentSource[$key] = [];
40
            }
41
42 4
            $currentSource = &$currentSource[$key];
43
        }
44
45 4
        $currentSource = $value;
46 4
    }
47
48 2
    public function exists(array $source, string $path): bool
49
    {
50
        try {
51 2
            $this->get($source, $path);
52 1
        } catch (NotFoundException $e) {
53 1
            return false;
54
        }
55
56 1
        return true;
57
    }
58
59 3
    public function remove(array &$source, string $path): void
60
    {
61 3
        $keys = explode($this->delimiter, $path);
62
63 3
        $lastKey = array_pop($keys);
64
65 3
        $currentSource = &$source;
66
67 3
        foreach ($keys as $key) {
68 3
            if (!array_key_exists($key, $currentSource)) {
69 1
                return;
70
            }
71
72 3
            $currentSource = &$currentSource[$key];
73
        }
74
75 2
        unset($currentSource[$lastKey]);
76 2
    }
77
}
78