CheckCircularReferencesPass.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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\Exception\ServiceCircularReferenceException;
  13. /**
  14. * Checks your services for circular references.
  15. *
  16. * References from method calls are ignored since we might be able to resolve
  17. * these references depending on the order in which services are called.
  18. *
  19. * Circular reference from method calls will only be detected at run-time.
  20. *
  21. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  22. */
  23. class CheckCircularReferencesPass implements CompilerPassInterface
  24. {
  25. private $currentPath;
  26. private $checkedNodes;
  27. /**
  28. * Checks the ContainerBuilder object for circular references.
  29. */
  30. public function process(ContainerBuilder $container)
  31. {
  32. $graph = $container->getCompiler()->getServiceReferenceGraph();
  33. $this->checkedNodes = [];
  34. foreach ($graph->getNodes() as $id => $node) {
  35. $this->currentPath = [$id];
  36. $this->checkOutEdges($node->getOutEdges());
  37. }
  38. }
  39. /**
  40. * Checks for circular references.
  41. *
  42. * @param ServiceReferenceGraphEdge[] $edges An array of Edges
  43. *
  44. * @throws ServiceCircularReferenceException when a circular reference is found
  45. */
  46. private function checkOutEdges(array $edges)
  47. {
  48. foreach ($edges as $edge) {
  49. $node = $edge->getDestNode();
  50. $id = $node->getId();
  51. if (empty($this->checkedNodes[$id])) {
  52. // Don't check circular references for lazy edges
  53. if (!$node->getValue() || (!$edge->isLazy() && !$edge->isWeak())) {
  54. $searchKey = array_search($id, $this->currentPath);
  55. $this->currentPath[] = $id;
  56. if (false !== $searchKey) {
  57. throw new ServiceCircularReferenceException($id, \array_slice($this->currentPath, $searchKey));
  58. }
  59. $this->checkOutEdges($node->getOutEdges());
  60. }
  61. $this->checkedNodes[$id] = true;
  62. array_pop($this->currentPath);
  63. }
  64. }
  65. }
  66. }