Completed
Pull Request — master (#410)
by Anton
22:49
created

Collection::set()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 4
nop 2
dl 0
loc 16
rs 8.8571
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
    static public function get(array $array, ...$keys)
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
24
    {
25
        $key = array_shift($keys);
26
27
        if (!isset($array[$key])) {
28
            return null;
29
        }
30
31
        if (empty($keys)) {
32
            return $array[$key] ?? null;
33
        }
34
35
        if (!is_array($array[$key])) {
36
            return null;
37
        }
38
39
        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
    static public function has(array $array, ...$keys) : bool
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
50
    {
51
        $key = array_shift($keys);
52
53
        if (!isset($array[$key])) {
54
            return false;
55
        }
56
57
        if (empty($keys)) {
58
            return isset($array[$key]);
59
        }
60
61
        if (!is_array($array[$key])) {
62
            return false;
63
        }
64
65
        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
    static public function set(array &$array, ...$keys)
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
77
    {
78
        if (count($keys) < 2) {
79
            throw new \InvalidArgumentException('Method `Collection::set()` is required minimum one key and value');
80
        }
81
82
        $value = array_pop($keys);
83
        while (count($keys) > 1) {
84
            $key = array_shift($keys);
85
            if (! isset($array[$key]) || ! is_array($array[$key])) {
86
                $array[$key] = [];
87
            }
88
            $array = &$array[$key];
89
        }
90
        $array[array_shift($keys)] = $value;
91
    }
92
}
93