Passed
Pull Request — master (#142)
by
unknown
03:50
created

BuilderRequireEncoder   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 43.48%

Importance

Changes 2
Bugs 1 Features 1
Metric Value
wmc 6
eloc 21
c 2
b 1
f 1
dl 0
loc 39
ccs 10
cts 23
cp 0.4348
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getDefaultOptions() 0 3 1
A supports() 0 16 3
A encode() 0 14 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Composer\Config\Util;
6
7
use Closure;
8
use Opis\Closure\ReflectionClosure;
9
use Riimu\Kit\PHPEncoder\Encoder\Encoder;
10
use Yiisoft\Composer\Config\Builder;
11
12
class BuilderRequireEncoder implements Encoder
13
{
14 24
    public function getDefaultOptions(): array
15
    {
16 24
        return [];
17
    }
18
19 24
    public function supports($value): bool
20
    {
21 24
        if (!$value instanceof Closure) {
22 18
            return false;
23
        }
24 20
        $reflection = new ReflectionClosure($value);
25
26 20
        $closureReflection = $reflection->getClosureScopeClass();
27
28 20
        if (null === $closureReflection) {
29
            return false;
30
        }
31
32 20
        $closureClassOwnerName = $closureReflection->getName();
33
34 20
        return is_a($closureClassOwnerName, Builder::class, true);
35
    }
36
37
    public function encode($value, $depth, array $options, callable $encode)
38
    {
39
        $reflection = new ReflectionClosure($value);
40
        $variables = $reflection->getStaticVariables();
41
        $config = strrpos($variables['config'], '.php') === false
42
            ? $variables['config'] . '.php'
43
            : $variables['config'];
44
45
        return str_replace(
46
            ['$config'],
47
            ["'$config'"],
48
            substr(
49
                $reflection->getCode(),
50
                16
51
            ),
52
        );
53
    }
54
}
55