ResettableServicePass.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. public function process(ContainerBuilder $container): void
  23. {
  24. if (!$container->has('services_resetter')) {
  25. return;
  26. }
  27. $services = $methods = [];
  28. foreach ($container->findTaggedServiceIds('kernel.reset', true) as $id => $tags) {
  29. $services[$id] = new Reference($id, ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE);
  30. foreach ($tags as $attributes) {
  31. if (!isset($attributes['method'])) {
  32. throw new RuntimeException(\sprintf('Tag "kernel.reset" requires the "method" attribute to be set on service "%s".', $id));
  33. }
  34. if (!isset($methods[$id])) {
  35. $methods[$id] = [];
  36. }
  37. if ('ignore' === ($attributes['on_invalid'] ?? null)) {
  38. $attributes['method'] = '?'.$attributes['method'];
  39. }
  40. $methods[$id][] = $attributes['method'];
  41. }
  42. }
  43. if (!$services) {
  44. $container->removeAlias('services_resetter');
  45. $container->removeDefinition('services_resetter');
  46. return;
  47. }
  48. $container->findDefinition('services_resetter')
  49. ->setArgument(0, new IteratorArgument($services))
  50. ->setArgument(1, $methods);
  51. }
  52. }