Passed
Pull Request — master (#7)
by Dmitriy
44:11 queued 29:04
created

Helper::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Yiisoft\Composer\Config\Utils;
4
5
use ReflectionException;
6
use Riimu\Kit\PHPEncoder\PHPEncoder;
7
8
use function in_array;
9
use function is_array;
10
use function is_int;
11
12
/**
13
 * Helper class.
14
 */
15
class Helper
16
{
17
    private PHPEncoder $encoder;
18
19
    public function __construct()
20
    {
21
        $encoder = new PHPEncoder([
22
            'object.format' => 'serialize',
23
        ]);
24
        $encoder->addEncoder(new ClosureEncoder(), true);
25
        $this->encoder = $encoder;
26
    }
27
28
    /**
29
     * @param array $args
30
     * @return array the merged array
31
     */
32
    public function mergeConfig(...$args): array
33
    {
34
        $res = array_shift($args) ?: [];
35
        foreach ($args as $items) {
36
            if (!is_array($items)) {
37
                continue;
38
            }
39
            foreach ($items as $k => $v) {
40
                if (is_int($k)) {
41
                    /// XXX skip repeated values
42
                    if (in_array($v, $res, true)) {
43
                        continue;
44
                    }
45
                    if (array_key_exists($k, $res)) {
46
                        $res[] = $v;
47
                    } else {
48
                        $res[$k] = $v;
49
                    }
50
                } elseif (is_array($v) && isset($res[$k]) && is_array($res[$k])) {
51
                    $res[$k] = $this->mergeConfig($res[$k], $v);
52
                } else {
53
                    $res[$k] = $v;
54
                }
55
            }
56
        }
57
58
        return $res;
59
    }
60
61
    public function fixConfig(array $config): array
62
    {
63
        $remove = false;
64
        foreach ($config as $key => &$value) {
65
            if (is_array($value)) {
66
                $value = $this->fixConfig($value);
67
            } elseif ($value instanceof RemoveArrayKeys) {
68
                $remove = true;
69
                unset($config[$key]);
70
            }
71
        }
72
        if ($remove) {
73
            return array_values($config);
74
        }
75
76
        return $config;
77
    }
78
79
    /**
80
     * Returns PHP-executable string representation of given value.
81
     * Uses Riimu/Kit-PHPEncoder based `var_export` alternative.
82
     * And Opis/Closure to dump closures as PHP code.
83
     *
84
     * @param mixed $value
85
     * @return string
86
     * @throws ReflectionException
87
     */
88
    public function exportVar($value): string
89
    {
90
        return $this->encoder->encode($value);
91
    }
92
}
93