CheckExceptionOnInvalidReferenceBehaviorPass.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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\ContainerBuilder;
  12. use Symfony\Component\DependencyInjection\ContainerInterface;
  13. use Symfony\Component\DependencyInjection\Definition;
  14. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  15. use Symfony\Component\DependencyInjection\Reference;
  16. /**
  17. * Checks that all references are pointing to a valid service.
  18. *
  19. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  20. */
  21. class CheckExceptionOnInvalidReferenceBehaviorPass implements CompilerPassInterface
  22. {
  23. private $container;
  24. private $sourceId;
  25. public function process(ContainerBuilder $container)
  26. {
  27. $this->container = $container;
  28. foreach ($container->getDefinitions() as $id => $definition) {
  29. $this->sourceId = $id;
  30. $this->processDefinition($definition);
  31. }
  32. }
  33. private function processDefinition(Definition $definition)
  34. {
  35. $this->processReferences($definition->getArguments());
  36. $this->processReferences($definition->getMethodCalls());
  37. $this->processReferences($definition->getProperties());
  38. }
  39. private function processReferences(array $arguments)
  40. {
  41. foreach ($arguments as $argument) {
  42. if (\is_array($argument)) {
  43. $this->processReferences($argument);
  44. } elseif ($argument instanceof Definition) {
  45. $this->processDefinition($argument);
  46. } elseif ($argument instanceof Reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $argument->getInvalidBehavior()) {
  47. $destId = (string) $argument;
  48. if (!$this->container->has($destId)) {
  49. throw new ServiceNotFoundException($destId, $this->sourceId);
  50. }
  51. }
  52. }
  53. }
  54. }