Passed
Pull Request — master (#24)
by Dmitriy
11:44
created

Helper   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 25
c 1
b 0
f 0
dl 0
loc 63
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A fixConfig() 0 16 5
A getEncoder() 0 7 2
A exportDefines() 0 9 2
A createEncoder() 0 8 1
A exportVar() 0 3 1
1
<?php
2
3
namespace Yiisoft\Composer\Config\Util;
4
5
use Riimu\Kit\PHPEncoder\PHPEncoder;
6
7
/**
8
 * Helper class.
9
 */
10
class Helper
11
{
12
    public static function fixConfig(array $config): array
13
    {
14
        $remove = false;
15
        foreach ($config as $key => &$value) {
16
            if (is_array($value)) {
17
                $value = static::fixConfig($value);
18
            } elseif ($value instanceof RemoveArrayKeys) {
19
                $remove = true;
20
                unset($config[$key]);
21
            }
22
        }
23
        if ($remove) {
24
            return array_values($config);
25
        }
26
27
        return $config;
28
    }
29
30
    public static function exportDefines(array $defines): string
31
    {
32
        $res = '';
33
        foreach ($defines as $key => $value) {
34
            $var = static::exportVar($value);
35
            $res .= "defined('$key') or define('$key', $var);\n";
36
        }
37
38
        return $res;
39
    }
40
41
    /**
42
     * Returns PHP-executable string representation of given value.
43
     * Uses Riimu/Kit-PHPEncoder based `var_export` alternative.
44
     * And Opis/Closure to dump closures as PHP code.
45
     * @param mixed $value
46
     * @return string
47
     * @throws \ReflectionException
48
     */
49
    public static function exportVar($value): string
50
    {
51
        return static::getEncoder()->encode($value);
52
    }
53
54
    private static $encoder;
55
56
    private static function getEncoder()
57
    {
58
        if (self::$encoder === null) {
59
            self::$encoder = static::createEncoder();
60
        }
61
62
        return self::$encoder;
63
    }
64
65
    private static function createEncoder()
66
    {
67
        $encoder = new PHPEncoder([
68
            'object.format' => 'serialize',
69
        ]);
70
        $encoder->addEncoder(new ClosureEncoder(), true);
71
72
        return $encoder;
73
    }
74
}
75