Completed
Push — master ( a7b476...58257b )
by Adrian
01:51
created

Arr::renameKeys()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 7
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 14
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace Sirius\Orm\Helpers;
5
6
class Arr
7
{
8
    public static function getChildren(array $arr, string $path, string $separator = '.')
9
    {
10
        $children  = [];
11
        $prefix    = $path . $separator;
12
        $prefixLen = strlen($prefix);
13
        foreach ($arr as $key => $value) {
14
            if (substr($key, 0, $prefixLen) != $prefix) {
15
                continue;
16
            }
17
            $children[substr($key, $prefixLen)] = $value;
18
        }
19
20
        return $children;
21
    }
22
23
    public static function ensureParents(array $arr, string $separator = '.'): array
24
    {
25
        foreach ($arr as $key => $value) {
26
            if (strpos($key, $separator)) {
27
                $parents = static::getParents($key, $separator);
28
                foreach ($parents as $parent) {
29
                    if (! isset($arr[$parent])) {
30
                        $arr[$parent] = null;
31
                    }
32
                }
33
            }
34
        }
35
36
        return $arr;
37
    }
38
39
    protected static function getParents(string $path, string $separator): array
40
    {
41
        $parts   = explode($separator, substr($path, 0, strrpos($path, $separator)));
42
        $current = '';
43
        $parents = [];
44
        foreach ($parts as $part) {
45
            $current   = $current . ($current ? $separator : '') . $part;
46
            $parents[] = $current;
47
        }
48
49
        return $parents;
50
    }
51
52
    public static function only(array $arr, array $keys)
53
    {
54
        return array_intersect_key($arr, array_flip((array)$keys));
55
    }
56
57
    public static function except(array $arr, $keys)
58
    {
59
        foreach ((array)$keys as $key) {
60
            unset($arr[$key]);
61
        }
62
63
        return $arr;
64
    }
65
66
    public static function renameKeys(array $arr, array $newNames)
67
    {
68
        if (empty($newNames)) {
69
            return $arr;
70
        }
71
72
        foreach (array_keys($newNames) as $name) {
73
            if (isset($arr[$name])) {
74
                $arr[$newNames[$name]] = $arr[$name];
75
                unset($arr[$name]);
76
            }
77
        }
78
79
        return $arr;
80
    }
81
}
82