ResettableServicePass.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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\HttpKernel\DependencyInjection;
  11. use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
  12. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  13. use Symfony\Component\DependencyInjection\ContainerBuilder;
  14. use Symfony\Component\DependencyInjection\ContainerInterface;
  15. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  16. use Symfony\Component\DependencyInjection\Reference;
  17. /**
  18. * @author Alexander M. Turek <me@derrabus.de>
  19. */
  20. class ResettableServicePass implements CompilerPassInterface
  21. {
  22. private $tagName;
  23. public function __construct(string $tagName = 'kernel.reset')
  24. {
  25. $this->tagName = $tagName;
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public function process(ContainerBuilder $container)
  31. {
  32. if (!$container->has('services_resetter')) {
  33. return;
  34. }
  35. $services = $methods = [];
  36. foreach ($container->findTaggedServiceIds($this->tagName, true) as $id => $tags) {
  37. $services[$id] = new Reference($id, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE);
  38. foreach ($tags as $attributes) {
  39. if (!isset($attributes['method'])) {
  40. throw new RuntimeException(sprintf('Tag "%s" requires the "method" attribute to be set.', $this->tagName));
  41. }
  42. if (!isset($methods[$id])) {
  43. $methods[$id] = [];
  44. }
  45. $methods[$id][] = $attributes['method'];
  46. }
  47. }
  48. if (!$services) {
  49. $container->removeAlias('services_resetter');
  50. $container->removeDefinition('services_resetter');
  51. return;
  52. }
  53. $container->findDefinition('services_resetter')
  54. ->setArgument(0, new IteratorArgument($services))
  55. ->setArgument(1, $methods);
  56. }
  57. }