Passed
Push — master ( a22915...aab382 )
by Alex
02:04 queued 27s
created

SetVariablePass::mergeScopeVariables()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

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