RegisterReverseContainerPass.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\DependencyInjection\Compiler;
  11. use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
  12. use Symfony\Component\DependencyInjection\ContainerBuilder;
  13. use Symfony\Component\DependencyInjection\ContainerInterface;
  14. use Symfony\Component\DependencyInjection\Definition;
  15. use Symfony\Component\DependencyInjection\Reference;
  16. /**
  17. * @author Nicolas Grekas <p@tchwork.com>
  18. */
  19. class RegisterReverseContainerPass implements CompilerPassInterface
  20. {
  21. private $beforeRemoving;
  22. private $serviceId;
  23. private $tagName;
  24. public function __construct(bool $beforeRemoving, string $serviceId = 'reverse_container', string $tagName = 'container.reversible')
  25. {
  26. $this->beforeRemoving = $beforeRemoving;
  27. $this->serviceId = $serviceId;
  28. $this->tagName = $tagName;
  29. }
  30. public function process(ContainerBuilder $container)
  31. {
  32. if (!$container->hasDefinition($this->serviceId)) {
  33. return;
  34. }
  35. $refType = $this->beforeRemoving ? ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE : ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  36. $services = [];
  37. foreach ($container->findTaggedServiceIds($this->tagName) as $id => $tags) {
  38. $services[$id] = new Reference($id, $refType);
  39. }
  40. if ($this->beforeRemoving) {
  41. // prevent inlining of the reverse container
  42. $services[$this->serviceId] = new Reference($this->serviceId, $refType);
  43. }
  44. $locator = $container->getDefinition($this->serviceId)->getArgument(1);
  45. if ($locator instanceof Reference) {
  46. $locator = $container->getDefinition((string) $locator);
  47. }
  48. if ($locator instanceof Definition) {
  49. foreach ($services as $id => $ref) {
  50. $services[$id] = new ServiceClosureArgument($ref);
  51. }
  52. $locator->replaceArgument(0, $services);
  53. } else {
  54. $locator->setValues($services);
  55. }
  56. }
  57. }