Test Failed
Push — master ( ecf42b...fd8dee )
by Alex
01:47
created

SetVariablePass::process()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6.0852

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 13
cts 15
cp 0.8667
rs 8.439
c 0
b 0
f 0
cc 6
eloc 14
nc 10
nop 1
crap 6.0852
1
<?php
2
declare(strict_types=1);
3
4
namespace AlexMasterov\PsyshBundle\DependencyInjection\Compiler;
5
6
use Symfony\Component\DependencyInjection\{
7
    Compiler\CompilerPassInterface,
8
    ContainerBuilder,
9
    Definition,
10
    Reference
11
};
12
13
class SetVariablePass implements CompilerPassInterface
14
{
15
    /** @const */
16
    const METHOD = 'setScopeVariables';
17
18
    /**
19
     * {@inheritdoc}
20
     */
21 6
    public function process(ContainerBuilder $container)
22
    {
23 6
        if (!$container->has('psysh.shell')) {
24 1
            return;
25
        }
26
27 5
        $variables = [];
28
29 5
        foreach ($container->findTaggedServiceIds('psysh.variable', true) as $id => [$attributes]) {
30 4
            $variable = $attributes['var'] ?? (\class_exists($id) ? $this->classify($id) : $id);
31 4
            $variables[$variable] = new Reference($id);
32
        }
33
34 5
        if (empty($variables)) {
35 1
            return;
36
        }
37
38 4
        $definition = $container->getDefinition('psysh.shell');
39
40 4
        if ($definition->hasMethodCall(self::METHOD)) {
41
            $this->mergeMethodCall($definition, $variables);
42
43
            return;
44
        }
45
46 4
        $definition->addMethodCall(self::METHOD, [$variables]);
47 4
    }
48
49
    // NameSpace\SomeName -> nameSpaceSomeName
50 2
    private function classify(string $spec): string
51
    {
52 2
        $parts = \explode('\\', $spec);
53
54 2
        if (!empty($parts[1])) {
55 1
            $parts[0] = \strtolower($parts[0]);
56
        }
57
58 2
        return \implode($parts);
59
    }
60
61
    private function mergeMethodCall(Definition $definition, array $variables): void
62
    {
63
        $calls = $definition->getMethodCalls();
64
65
        foreach ($calls as $call => [$method, $arguments]) {
66
            if (self::METHOD === $method) {
67
                foreach ($arguments as $argument) {
68
                    $variables += $argument;
69
                }
70
                unset($calls[$call]);
71
            }
72
        }
73
74
        $mergedCalls += [
0 ignored issues
show
Bug introduced by
The variable $mergedCalls does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
75
            [self::METHOD, [$variables]],
76
        ];
77
78
        $definition->setMethodCalls($mergedCalls);
79
    }
80
}
81