Completed
Push — master ( f5b8f3...bcb3b5 )
by Alexandr
01:26
created

ArrHelper::unflatten()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 3
nop 1
crap 4
1
<?php
2
3
namespace Bricks\Helper;
4
5
6
class ArrHelper
7
{
8
    /**
9
     * @param array $array
10
     * @return bool
11
     */
12
    public static function isStrKeysArray(array $array): bool
13
    {
14 10
        $filtered = array_filter($array, function ($key) {
15 10
            return !is_string($key);
16 10
        }, ARRAY_FILTER_USE_KEY);
17
18 10
        return empty($filtered);
19
    }
20
21
    /**
22
     * @param array $array
23
     * @return array
24
     */
25 12
    public static function unflatten(array $array): array
26
    {
27 12
        $output = [];
28 12
        foreach ($array as $key => $value) {
29 12
            static::set($output, $key, $value);
0 ignored issues
show
Bug introduced by
Since set() is declared private, calling it with static will lead to errors in possible sub-classes. You can either use self, or increase the visibility of set() to at least protected.

Let’s assume you have a class which uses late-static binding:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
}

public static function getSomeVariable()
{
    return static::getTemperature();
}

}

The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the getSomeVariable() on that sub-class, you will receive a runtime error:

class YourSubClass extends YourClass {
      private static function getTemperature() {
        return "-182 °C";
    }
}

print YourSubClass::getSomeVariable(); // Will cause an access error.

In the case above, it makes sense to update SomeClass to use self instead:

class YourClass
{
    private static function getTemperature() {
        return "3422 °C";
    }

    public static function getSomeVariable()
    {
        return self::getTemperature();
    }
}
Loading history...
30 12
            if (is_array($value) && strpos($key, '.') === false) {
31 12
                $output[$key] = static::unflatten($value);
32
            }
33
        }
34 12
        return $output;
35
    }
36
37
    /**
38
     * @param array $array
39
     * @param string $key
40
     * @param mixed $value
41
     */
42 12
    private static function set(array &$array, string $key, $value)
43
    {
44 12
        $keys = explode('.', $key);
45 12
        while (count($keys) > 1) {
46 3
            $key = array_shift($keys);
47 3
            if (!isset($array[$key]) || !is_array($array[$key])) {
48 3
                $array[$key] = [];
49
            }
50 3
            $array =& $array[$key];
51
        }
52 12
        $array[array_shift($keys)] = $value;
53
    }
54
}