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
|
7 |
|
public function process(ContainerBuilder $container) |
22
|
|
|
{ |
23
|
7 |
|
if (!$container->has('psysh.shell')) { |
24
|
1 |
|
return; |
25
|
|
|
} |
26
|
|
|
|
27
|
6 |
|
$variables = []; |
28
|
|
|
|
29
|
6 |
|
foreach ($container->findTaggedServiceIds('psysh.variable', true) as $id => [$attributes]) { |
30
|
5 |
|
$variable = $attributes['var'] ?? (\class_exists($id) ? $this->classify($id) : $id); |
31
|
5 |
|
$variables[$variable] = new Reference($id); |
32
|
|
|
} |
33
|
|
|
|
34
|
6 |
|
if (empty($variables)) { |
35
|
1 |
|
return; |
36
|
|
|
} |
37
|
|
|
|
38
|
5 |
|
$definition = $container->getDefinition('psysh.shell'); |
39
|
|
|
|
40
|
5 |
|
if ($definition->hasMethodCall(self::METHOD)) { |
41
|
1 |
|
$this->mergeMethodCall($definition, $variables); |
42
|
|
|
|
43
|
1 |
|
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
|
1 |
|
private function mergeMethodCall(Definition $definition, array $variables): void |
62
|
|
|
{ |
63
|
1 |
|
$calls = $definition->getMethodCalls(); |
64
|
|
|
|
65
|
1 |
|
foreach ($calls as $call => [$method, $arguments]) { |
66
|
1 |
|
if (self::METHOD === $method) { |
67
|
1 |
|
foreach ($arguments as $argument) { |
68
|
1 |
|
$variables += $argument; |
69
|
|
|
} |
70
|
1 |
|
unset($calls[$call]); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
$calls += [ |
75
|
1 |
|
[self::METHOD, [$variables]], |
76
|
|
|
]; |
77
|
|
|
|
78
|
1 |
|
$definition->setMethodCalls($calls); |
79
|
1 |
|
} |
80
|
|
|
} |
81
|
|
|
|