ArrayUtils::arrayFlatten()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 8
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 15
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Locastic\SymfonyTranslationBundle\Utils;
6
7
use Symfony\Component\PropertyAccess\PropertyAccessor;
8
9
use function array_merge_recursive;
10
use function explode;
11
use function is_array;
12
13
final class ArrayUtils
14
{
15
    public static function arrayFlatten(array $translations, string $prefix = ''): array
16
    {
17
        $result = array();
18
19
        foreach ($translations as $key => $value) {
20
            $new_key = $prefix . (empty($prefix) ? '' : '.') . $key;
21
22
            if (is_array($value)) {
23
                $result = array_merge_recursive($result, self::arrayFlatten($value, $new_key));
24
            } else {
25
                $result[$new_key] = $value;
26
            }
27
        }
28
29
        return $result;
30
    }
31
32
    public static function recursiveKsort(array &$array): bool
33
    {
34
        foreach ($array as &$value) {
35
            if (is_array($value)) {
36
                self::recursiveKsort($value);
37
            }
38
        }
39
40
        return ksort($array);
41
    }
42
43
    public static function keyToArray(string $translationKey, string $value): array
44
    {
45
        $result = [];
46
        $path = '';
47
        $explodedKey = explode('.', $translationKey);
48
        foreach ($explodedKey as $key) {
49
            if (empty($key)) {
50
                continue;
51
            }
52
            $path .= '[' . $key . ']';
53
        }
54
        $propertyAccessor = new PropertyAccessor();
55
        $propertyAccessor->setValue($result, $path, $value);
56
57
        return $result;
58
    }
59
}
60