PathCollection   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Test Coverage

Coverage 68.75%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 28
dl 0
loc 77
rs 10
c 1
b 0
f 0
ccs 22
cts 32
cp 0.6875
wmc 14

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A pathExists() 0 3 1
A checkPathExists() 0 20 4
A setValueInPath() 0 14 3
A getValueInPath() 0 14 4
A toArray() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Shlinkio\Shlink\Config\Collection;
6
7
use function array_key_exists;
8
use function array_shift;
9
use function count;
10
use function is_array;
11
12
final class PathCollection
13
{
14
    private array $array;
15
16 16
    public function __construct(array $array = [])
17
    {
18 16
        $this->array = $array;
19
    }
20
21 8
    public function pathExists(array $path): bool
22
    {
23 8
        return $this->checkPathExists($path, $this->array);
24
    }
25
26 8
    private function checkPathExists(array $path, array $array): bool
27
    {
28
        // As soon as a step is not found, the path does not exist
29 8
        $step = array_shift($path);
30 8
        if (! array_key_exists($step, $array)) {
31 3
            return false;
32
        }
33
34
        // Once the path is empty, we have found all the parts in the path
35 6
        if (empty($path)) {
36 4
            return true;
37
        }
38
39
        // If current value is not an array, then we have not found the path
40 4
        $newArray = $array[$step];
41 4
        if (! is_array($newArray)) {
42 1
            return false;
43
        }
44
45 4
        return $this->checkPathExists($path, $newArray);
46
    }
47
48
    /**
49
     * @return mixed
50
     */
51 8
    public function getValueInPath(array $path)
52
    {
53 8
        $array = $this->array;
54
55
        do {
56 8
            $step = array_shift($path);
57 8
            if (! is_array($array) || ! array_key_exists($step, $array)) {
58 4
                return null;
59
            }
60
61 6
            $array = $array[$step];
62 6
        } while (! empty($path));
63
64 4
        return $array;
65
    }
66
67
    /**
68
     * @param mixed $value
69
     */
70
    public function setValueInPath($value, array $path): void
71
    {
72
        $ref =& $this->array;
73
74
        while (count($path) > 1) {
75
            $currentKey = array_shift($path);
76
            if (! array_key_exists($currentKey, $ref)) {
77
                $ref[$currentKey] = [];
78
            }
79
80
            $ref =& $ref[$currentKey];
81
        }
82
83
        $ref[array_shift($path)] = $value;
84
    }
85
86
    public function toArray(): array
87
    {
88
        return $this->array;
89
    }
90
}
91