Completed
Pull Request — master (#242)
by Alejandro
01:36
created

PathCollection::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Common\Collection;
5
6
use function array_key_exists;
7
use function array_shift;
8
use function is_array;
9
10
final class PathCollection
11
{
12
    /**
13
     * @var array
14
     */
15
    private $array;
16
17 18
    public function __construct(array $array)
18
    {
19 18
        $this->array = $array;
20 18
    }
21
22 10
    public function pathExists(array $path): bool
23
    {
24 10
        return $this->checkPathExists($path, $this->array);
25
    }
26
27 10
    private function checkPathExists(array $path, array $array): bool
28
    {
29
        // As soon as a step is not found, the path does not exist
30 10
        $step = array_shift($path);
31 10
        if (! array_key_exists($step, $array)) {
32 5
            return false;
33
        }
34
35
        // Once the path is empty, we have found all the parts in the path
36 7
        if (empty($path)) {
37 5
            return true;
38
        }
39
40
        // If current value is not an array, then we have not found the path
41 5
        $newArray = $array[$step];
42 5
        if (! is_array($newArray)) {
43 1
            return false;
44
        }
45
46 5
        return $this->checkPathExists($path, $newArray);
47
    }
48
49
    /**
50
     * @return mixed
51
     */
52 9
    public function getValueInPath(array $path)
53
    {
54 9
        $array = $this->array;
55
56
        do {
57 9
            $step = array_shift($path);
58 9
            if (! is_array($array) || ! array_key_exists($step, $array)) {
59 4
                return null;
60
            }
61
62 7
            $array = $array[$step];
63 7
        } while (! empty($path));
64
65 5
        return $array;
66
    }
67
}
68