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

SetVariablePass::classify()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 2
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