Helper::getEncoder()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 10
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Composer\Config\Util;
6
7
use Riimu\Kit\PHPEncoder\PHPEncoder;
8
9
/**
10
 * Helper class.
11
 */
12
class Helper
13
{
14
    /**
15
     * Returns PHP-executable string representation of given value.
16
     * Uses Riimu/Kit-PHPEncoder based `var_export` alternative.
17
     * And Opis/Closure to dump closures as PHP code.
18
     *
19
     * @param mixed $value
20
     *
21
     * @throws \ReflectionException
22
     *
23
     * @return string
24
     */
25 24
    public static function exportVar($value): string
26
    {
27 24
        return static::getEncoder()->encode($value);
28
    }
29
30
    private static ?PHPEncoder $encoder = null;
31
32 24
    private static function getEncoder(): PHPEncoder
33
    {
34 24
        if (self::$encoder === null) {
35 2
            self::$encoder = static::createEncoder();
36
        }
37
38 24
        return self::$encoder;
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::encoder could return the type null which is incompatible with the type-hinted return Riimu\Kit\PHPEncoder\PHPEncoder. Consider adding an additional type-check to rule them out.
Loading history...
39
    }
40
41 2
    private static function createEncoder(): PHPEncoder
42
    {
43 2
        $encoder = new PHPEncoder([
44 2
            'object.format' => 'serialize',
45
        ]);
46 2
        $encoder->addEncoder(new ClosureEncoder(), true);
47 2
        $encoder->addEncoder(new EnvEncoder(), true);
48 2
        $encoder->addEncoder(new ObjectEncoder(), true);
49 2
        $encoder->addEncoder(new BuilderRequireEncoder(), true);
50
51 2
        return $encoder;
52
    }
53
}
54