ResettableServicePass.php 2.1 KB

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