Passed
Pull Request — master (#53)
by Dmitriy
14:13
created

EnvEncoder   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 14
c 1
b 0
f 0
dl 0
loc 33
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A supports() 0 15 4
A encode() 0 9 1
A getDefaultOptions() 0 3 1
1
<?php
2
3
namespace Yiisoft\Composer\Config\Util;
4
5
use Closure;
6
use Opis\Closure\ReflectionClosure;
7
use Riimu\Kit\PHPEncoder\Encoder\Encoder;
8
use Yiisoft\Composer\Config\Env;
9
10
class EnvEncoder implements Encoder
11
{
12
    public function getDefaultOptions(): array
13
    {
14
        return [];
15
    }
16
17
    public function supports($value): bool
18
    {
19
        if (!$value instanceof Closure) {
20
            return false;
21
        }
22
        $reflection = new ReflectionClosure($value);
23
24
        $closureReflection = ($reflection)->getClosureScopeClass();
25
        $closureClassOwnerName = $closureReflection->getName();
26
27
        if ($closureClassOwnerName !== Env::class && !is_subclass_of($closureClassOwnerName, Env::class)) {
28
            return false;
29
        }
30
31
        return strpos($reflection->getCode(), 'fn() => $_ENV') !== false;
32
    }
33
34
    public function encode($value, $depth, array $options, callable $encode)
35
    {
36
        $reflection = new ReflectionClosure($value);
37
        $value = current($reflection->getStaticVariables());
38
39
        return substr(
40
            str_replace('$key', "'$value'", $reflection->getCode()),
41
            8,
42
            -1
43
        );
44
    }
45
}
46