|
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
|
5 |
|
public function process(ContainerBuilder $container) |
|
18
|
|
|
{ |
|
19
|
5 |
|
if (false === $container->has('psysh.shell')) { |
|
20
|
|
|
return; |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
5 |
|
$services = $container->findTaggedServiceIds('psysh.variable', true); |
|
24
|
5 |
|
if (empty($services)) { |
|
25
|
|
|
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, $args]) { |
|
49
|
1 |
|
if ('setScopeVariables' === $method) { |
|
50
|
1 |
|
foreach ($args as $arg) { |
|
51
|
1 |
|
$variables += $arg; |
|
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 |
|
return \str_replace('\\', '', \lcfirst(\ucwords(\strtolower($spec), '\\'))); |
|
67
|
5 |
|
}; |
|
68
|
|
|
|
|
69
|
5 |
|
$scopeVariables = []; |
|
70
|
5 |
|
foreach ($services as $id => [$variable]) { |
|
71
|
5 |
|
$variable = $variable['name'] ?? (\class_exists($id) ? $classify($id) : $id); |
|
72
|
5 |
|
$scopeVariables[$variable] = new Reference($id); |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
5 |
|
return $scopeVariables; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|