|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Zenstruck\Foundry\InMemory\DependencyInjection; |
| 6 | + |
| 7 | +use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; |
| 8 | +use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass; |
| 9 | +use Symfony\Component\DependencyInjection\ContainerBuilder; |
| 10 | +use Symfony\Component\DependencyInjection\Reference; |
| 11 | +use Zenstruck\Foundry\InMemory\InMemoryFactoryRegistry; |
| 12 | + |
| 13 | +/** |
| 14 | + * @internal |
| 15 | + * @author Nicolas PHILIPPE <[email protected]> |
| 16 | + */ |
| 17 | +final class InMemoryCompilerPass implements CompilerPassInterface |
| 18 | +{ |
| 19 | + public function process(ContainerBuilder $container): void |
| 20 | + { |
| 21 | + // create a service locator with all "in memory" repositories, indexed by target class |
| 22 | + $inMemoryRepositoriesServices = $container->findTaggedServiceIds('foundry.in_memory.repository'); |
| 23 | + $inMemoryRepositoriesLocator = ServiceLocatorTagPass::register( |
| 24 | + $container, |
| 25 | + array_combine( |
| 26 | + array_map( |
| 27 | + static function (array $tags) { |
| 28 | + if (\count($tags) !== 1) { |
| 29 | + throw new \LogicException('Cannot have multiple tags "foundry.in_memory.repository" on a service!'); |
| 30 | + } |
| 31 | + |
| 32 | + return $tags[0]['class'] ?? throw new \LogicException('Invalid tag definition of "foundry.in_memory.repository".'); |
| 33 | + }, |
| 34 | + array_values($inMemoryRepositoriesServices) |
| 35 | + ), |
| 36 | + array_map( |
| 37 | + static fn(string $inMemoryRepositoryId) => new Reference($inMemoryRepositoryId), |
| 38 | + array_keys($inMemoryRepositoriesServices) |
| 39 | + ), |
| 40 | + ) |
| 41 | + ); |
| 42 | + |
| 43 | + // todo: should we check we only have a 1 repository per class? |
| 44 | +
|
| 45 | + $container->findDefinition('.zenstruck_foundry.in_memory.repository_registry') |
| 46 | + ->setArgument('$inMemoryRepositories', $inMemoryRepositoriesLocator) |
| 47 | + ; |
| 48 | + } |
| 49 | +} |
0 commit comments