Passed
Push — master ( ca35e1...013463 )
by Alex
02:13
created

SetVariablePass::process()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 15
cts 15
cp 1
rs 8.439
c 0
b 0
f 0
cc 6
eloc 14
nc 10
nop 1
crap 6
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
    /**
16
     * {@inheritdoc}
17
     */
18 7
    public function process(ContainerBuilder $container)
19
    {
20 7
        if (!$container->has('psysh.shell')) {
21 1
            return;
22
        }
23
24 6
        $variables = [];
25
26 6
        foreach ($container->findTaggedServiceIds('psysh.variable', true) as $id => [$attributes]) {
27 5
            $variable = $attributes['var'] ?? (\class_exists($id) ? $this->classify($id) : $id);
28 5
            $variables[$variable] = new Reference($id);
29
        }
30
31 6
        if (empty($variables)) {
32 1
            return;
33
        }
34
35 5
        $definition = $container->getDefinition('psysh.shell');
36
37 5
        if ($definition->hasMethodCall('setScopeVariables')) {
38 1
            $this->mergeScopeVariables($definition, $variables);
39
40 1
            return;
41
        }
42
43 4
        $definition->addMethodCall('setScopeVariables', [$variables]);
44 4
    }
45
46
    // NameSpace\SomeName -> nameSpaceSomeName
47 2
    private function classify(string $spec): string
48
    {
49 2
        $parts = \explode('\\', $spec);
50
51 2
        if (!empty($parts[1])) {
52 1
            $parts[0] = \strtolower($parts[0]);
53
        }
54
55 2
        return \implode($parts);
56
    }
57
58 1
    private function mergeScopeVariables(Definition $definition, array $variables): void
59
    {
60 1
        $calls = $definition->getMethodCalls();
61
62 1
        foreach ($calls as $call => [$method, $arguments]) {
63 1
            if ('setScopeVariables' === $method) {
64 1
                foreach ($arguments as $argument) {
65 1
                    $variables += $argument;
66
                }
67 1
                unset($calls[$call]);
68
            }
69
        }
70
71
        $calls += [
72 1
            ['setScopeVariables', [$variables]],
73
        ];
74
75 1
        $definition->setMethodCalls($calls);
76 1
    }
77
}
78