Drupal investigation

RemoveUnusedDefinitionsPass.php 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. /**
  13. * Removes unused service definitions from the container.
  14. *
  15. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  16. */
  17. class RemoveUnusedDefinitionsPass implements RepeatablePassInterface
  18. {
  19. private $repeatedPass;
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function setRepeatedPass(RepeatedPass $repeatedPass)
  24. {
  25. $this->repeatedPass = $repeatedPass;
  26. }
  27. /**
  28. * Processes the ContainerBuilder to remove unused definitions.
  29. *
  30. * @param ContainerBuilder $container
  31. */
  32. public function process(ContainerBuilder $container)
  33. {
  34. $compiler = $container->getCompiler();
  35. $formatter = $compiler->getLoggingFormatter();
  36. $graph = $compiler->getServiceReferenceGraph();
  37. $hasChanged = false;
  38. foreach ($container->getDefinitions() as $id => $definition) {
  39. if ($definition->isPublic()) {
  40. continue;
  41. }
  42. if ($graph->hasNode($id)) {
  43. $edges = $graph->getNode($id)->getInEdges();
  44. $referencingAliases = array();
  45. $sourceIds = array();
  46. foreach ($edges as $edge) {
  47. $node = $edge->getSourceNode();
  48. $sourceIds[] = $node->getId();
  49. if ($node->isAlias()) {
  50. $referencingAliases[] = $node->getValue();
  51. }
  52. }
  53. $isReferenced = (count(array_unique($sourceIds)) - count($referencingAliases)) > 0;
  54. } else {
  55. $referencingAliases = array();
  56. $isReferenced = false;
  57. }
  58. if (1 === count($referencingAliases) && false === $isReferenced) {
  59. $container->setDefinition((string) reset($referencingAliases), $definition);
  60. $definition->setPublic(true);
  61. $container->removeDefinition($id);
  62. $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'replaces alias '.reset($referencingAliases)));
  63. } elseif (0 === count($referencingAliases) && false === $isReferenced) {
  64. $container->removeDefinition($id);
  65. $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'unused'));
  66. $hasChanged = true;
  67. }
  68. }
  69. if ($hasChanged) {
  70. $this->repeatedPass->setRepeat();
  71. }
  72. }
  73. }