Completed
Push — master ( 4ecd26...84af35 )
by Anton
12s
created

Collection::has()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 2
dl 0
loc 18
ccs 9
cts 9
cp 1
crap 4
rs 9.2
c 0
b 0
f 0
1
<?php
2
/**
3
 * @namespace
4
 */
5
6
namespace Bluz\Common;
7
8
/**
9
 * Collection
10
 *
11
 * @package  Bluz\Common
12
 * @author   Anton Shevchuk
13
 */
14
class Collection
15
{
16
    /**
17
     * Get an element to array by key and sub-keys
18
     *
19
     * @param array $array
20
     * @param array ...$keys
21
     * @return mixed|null
22
     */
23 709
    public static function get(array $array, ...$keys)
24
    {
25 709
        $key = array_shift($keys);
26
27 709
        if (!isset($array[$key])) {
28 5
            return null;
29
        }
30
31 709
        if (empty($keys)) {
32 709
            return $array[$key] ?? null;
33
        }
34
35 9
        if (!is_array($array[$key])) {
36 1
            return null;
37
        }
38
39 8
        return self::get($array[$key], ...$keys);
40
    }
41
42
    /**
43
     * Check an element of array by key and sub-keys
44
     *
45
     * @param array $array
46
     * @param array ...$keys
47
     * @return bool
48
     */
49 14
    public static function has(array $array, ...$keys) : bool
50
    {
51 14
        $key = array_shift($keys);
52
53 14
        if (!isset($array[$key])) {
54 5
            return false;
55
        }
56
57 12
        if (empty($keys)) {
58 8
            return isset($array[$key]);
59
        }
60
61 8
        if (!is_array($array[$key])) {
62 1
            return false;
63
        }
64
65 7
        return self::has($array[$key], ...$keys);
66
    }
67
68
    /**
69
     * Add an element of array by key and sub-keys
70
     *
71
     * @param array $array
72
     * @param array ...$keys
73
     * @return void
74
     * @throws \InvalidArgumentException
75
     */
76 4
    public static function set(array &$array, ...$keys)
77
    {
78 4
        if (count($keys) < 2) {
79 2
            throw new \InvalidArgumentException('Method `Collection::set()` is required minimum one key and value');
80
        }
81
82 2
        $value = array_pop($keys);
83 2
        while (count($keys) > 1) {
84 2
            $key = array_shift($keys);
85 2
            if (! isset($array[$key]) || ! is_array($array[$key])) {
86 2
                $array[$key] = [];
87
            }
88 2
            $array = &$array[$key];
89
        }
90 2
        $array[array_shift($keys)] = $value;
91 2
    }
92
}
93