Passed
Push — master ( f505e3...62b965 )
by Herberto
02:01
created

ArrayHelper::mapRecursive()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Hgraca\Helper;
4
5
use Hgraca\Helper\Concept\HelperAbstract;
6
7
final class ArrayHelper extends HelperAbstract
8
{
9
    /**
10
     * Renames the given data array keys for the corresponding values in $mapper.
11
     * If $mapper does not have the key, the name is preserved.
12
     *
13
     * @param array $mapper [from => to]
14
     */
15 1
    public static function renameKeys(array $data, array $mapper): array
16
    {
17 1
        foreach ($mapper as $from => $to) {
18 1
            if (isset($data[$from])) {
19 1
                $data[$to] = $data[$from];
20 1
                unset($data[$from]);
21
            }
22
        }
23
24 1
        return $data;
25
    }
26
27
    /**
28
     * Fetch array data in dot notation path
29
     *
30
     * @return mixed|null
31
     */
32 4
    public static function extract(array $data, string $path)
33
    {
34 4
        if ('' === $path) {
35 1
            return $data;
36
        }
37
38 3
        $steps = explode('.', $path);
39 3
        $actual = $data;
40 3
        foreach ($steps as $step) {
41 3
            if (!array_key_exists($step, $actual)) {
42 1
                return null;
43
            }
44
45 2
            $actual = $actual[$step];
46
        }
47
48 2
        return $actual;
49
    }
50
51 4
    public static function isTwoDimensional(array $array): bool
52
    {
53 4
        $array = array_values($array);
54 4
        return isset($array[0]) && is_array($array[0]);
55
    }
56
57
    /**
58
     * Same as array_map, but recursive
59
     */
60 2
    public static function mapRecursive(callable $func, array $array)
61
    {
62 2
        return filter_var($array, \FILTER_CALLBACK, ['options' => $func]);
63
    }
64
}
65