SetVariablePass   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 12
lcom 0
cbo 3
dl 0
loc 65
ccs 30
cts 30
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
B process() 0 26 6
A classify() 0 10 2
A mergeMethodCall() 0 19 4
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
use function class_exists;
13
use function explode;
14
use function implode;
15
use function strtolower;
16
17
class SetVariablePass implements CompilerPassInterface
18
{
19
    /** @const string */
20
    const METHOD = 'setScopeVariables';
21
22
    /** {@inheritdoc} */
23 7
    public function process(ContainerBuilder $container)
24
    {
25 7
        if (!$container->has('psysh.shell')) {
26 1
            return;
27
        }
28
29 6
        $variables = [];
30
31 6
        foreach ($container->findTaggedServiceIds('psysh.variable', true) as $id => [$attributes]) {
32 5
            $variable = $attributes['var'] ?? (class_exists($id) ? $this->classify($id) : $id);
33 5
            $variables[$variable] = new Reference($id);
34
        }
35
36 6
        if (empty($variables)) {
37 1
            return;
38
        }
39
40 5
        $definition = $container->getDefinition('psysh.shell');
41
42 5
        if ($definition->hasMethodCall(self::METHOD)) {
43 1
            $this->mergeMethodCall($definition, $variables);
44 1
            return;
45
        }
46
47 4
        $definition->addMethodCall(self::METHOD, [$variables]);
48 4
    }
49
50
    // NameSpace\SomeName -> nameSpaceSomeName
51 2
    private function classify(string $spec): string
52
    {
53 2
        $parts = explode('\\', $spec);
54
55 2
        if (!empty($parts[1])) {
56 1
            $parts[0] = strtolower($parts[0]);
57
        }
58
59 2
        return implode($parts);
60
    }
61
62 1
    private function mergeMethodCall(Definition $definition, array $variables): void
63
    {
64 1
        $calls = $definition->getMethodCalls();
65
66 1
        foreach ($calls as $call => [$method, $arguments]) {
67 1
            if (self::METHOD === $method) {
68 1
                foreach ($arguments as $argument) {
69 1
                    $variables += $argument;
70
                }
71 1
                unset($calls[$call]);
72
            }
73
        }
74
75
        $calls += [
76 1
            [self::METHOD, [$variables]],
77
        ];
78
79 1
        $definition->setMethodCalls($calls);
80 1
    }
81
}
82