-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathAutowireWithMutexPass.php
More file actions
62 lines (51 loc) · 2.25 KB
/
AutowireWithMutexPass.php
File metadata and controls
62 lines (51 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
declare(strict_types=1);
namespace App\Infrastructure\DependencyInjection\Mutex;
use App\Infrastructure\Mutex\LockName;
use App\Infrastructure\Mutex\Mutex;
use Symfony\Component\DependencyInjection\Argument\BoundArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
class AutowireWithMutexPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
$createdMutexes = [];
foreach ($container->findTaggedServiceIds('app.mutex') as $id => $tags) {
$tag = array_first($tags);
if (!$mutexDefinitionId = $tag['mutex'] ?? null) {
continue;
}
if (!\in_array($mutexDefinitionId, $createdMutexes, true)) {
$definitionArguments = [];
if (!$constructorParams = new \ReflectionClass(Mutex::class)->getConstructor()?->getParameters() ?? []) {
continue;
}
[$prefix, $lockName] = explode('.', (string) $mutexDefinitionId);
foreach ($constructorParams as $param) {
$type = $param->getType();
assert($type instanceof \ReflectionNamedType);
$definitionArguments[] = match ($param->getName()) {
'lockName' => LockName::from($lockName),
default => new Reference($type->getName()),
};
}
$container->setDefinition(
id: $mutexDefinitionId,
definition: new Definition(
class: Mutex::class,
arguments: $definitionArguments
)
);
$createdMutexes[] = $mutexDefinitionId;
}
$definition = $container->getDefinition($id);
$binding = new BoundArgument(new Reference($mutexDefinitionId));
$bindings = $definition->getBindings();
$bindings[Mutex::class] = $binding;
$definition->setBindings($bindings);
}
}
}