CheckExceptionOnInvalidReferenceBehaviorPass.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace Symfony\Component\DependencyInjection\Compiler;
  3. use Symfony\Component\DependencyInjection\Definition;
  4. use Symfony\Component\DependencyInjection\Exception\NonExistentServiceException;
  5. use Symfony\Component\DependencyInjection\ContainerInterface;
  6. use Symfony\Component\DependencyInjection\Reference;
  7. use Symfony\Component\DependencyInjection\ContainerBuilder;
  8. /**
  9. * Checks that all references are pointing to a valid service.
  10. *
  11. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  12. */
  13. class CheckExceptionOnInvalidReferenceBehaviorPass implements CompilerPassInterface
  14. {
  15. private $container;
  16. private $sourceId;
  17. public function process(ContainerBuilder $container)
  18. {
  19. $this->container = $container;
  20. foreach ($container->getDefinitions() as $id => $definition) {
  21. $this->sourceId = $id;
  22. $this->processDefinition($definition);
  23. }
  24. }
  25. private function processDefinition(Definition $definition)
  26. {
  27. $this->processReferences($definition->getArguments());
  28. $this->processReferences($definition->getMethodCalls());
  29. $this->processReferences($definition->getProperties());
  30. }
  31. private function processReferences(array $arguments)
  32. {
  33. foreach ($arguments as $argument) {
  34. if (is_array($argument)) {
  35. $this->processReferences($argument);
  36. } else if ($argument instanceof Definition) {
  37. $this->processDefinition($argument);
  38. } else if ($argument instanceof Reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $argument->getInvalidBehavior()) {
  39. $destId = (string) $argument;
  40. if (!$this->container->has($destId)) {
  41. throw new NonExistentServiceException($destId, $this->sourceId);
  42. }
  43. }
  44. }
  45. }
  46. }