Passed
Pull Request — master (#24)
by Dmitriy
37:45 queued 22:43
created

Helper::exportDefines()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 9
rs 10
cc 2
nc 2
nop 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 exportDefines(array $defines): string
13
    {
14
        $res = '';
15
        foreach ($defines as $key => $value) {
16
            $var = static::exportVar($value);
17
            $res .= "defined('$key') or define('$key', $var);\n";
18
        }
19
20
        return $res;
21
    }
22
23
    /**
24
     * Returns PHP-executable string representation of given value.
25
     * Uses Riimu/Kit-PHPEncoder based `var_export` alternative.
26
     * And Opis/Closure to dump closures as PHP code.
27
     * @param mixed $value
28
     * @return string
29
     * @throws \ReflectionException
30
     */
31
    public static function exportVar($value): string
32
    {
33
        return static::getEncoder()->encode($value);
34
    }
35
36
    private static $encoder;
37
38
    private static function getEncoder()
39
    {
40
        if (self::$encoder === null) {
41
            self::$encoder = static::createEncoder();
42
        }
43
44
        return self::$encoder;
45
    }
46
47
    private static function createEncoder()
48
    {
49
        $encoder = new PHPEncoder([
50
            'object.format' => 'serialize',
51
        ]);
52
        $encoder->addEncoder(new ClosureEncoder(), true);
53
54
        return $encoder;
55
    }
56
}
57