RemoveUnusedDefinitionsPass.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. public function process(ContainerBuilder $container)
  31. {
  32. $compiler = $container->getCompiler();
  33. $formatter = $compiler->getLoggingFormatter();
  34. $graph = $compiler->getServiceReferenceGraph();
  35. $hasChanged = false;
  36. foreach ($container->getDefinitions() as $id => $definition) {
  37. if ($definition->isPublic()) {
  38. continue;
  39. }
  40. if ($graph->hasNode($id)) {
  41. $edges = $graph->getNode($id)->getInEdges();
  42. $referencingAliases = array();
  43. $sourceIds = array();
  44. foreach ($edges as $edge) {
  45. $node = $edge->getSourceNode();
  46. $sourceIds[] = $node->getId();
  47. if ($node->isAlias()) {
  48. $referencingAliases[] = $node->getValue();
  49. }
  50. }
  51. $isReferenced = (\count(array_unique($sourceIds)) - \count($referencingAliases)) > 0;
  52. } else {
  53. $referencingAliases = array();
  54. $isReferenced = false;
  55. }
  56. if (1 === \count($referencingAliases) && false === $isReferenced) {
  57. $container->setDefinition((string) reset($referencingAliases), $definition);
  58. $definition->setPublic(true);
  59. $container->removeDefinition($id);
  60. $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'replaces alias '.reset($referencingAliases)));
  61. } elseif (0 === \count($referencingAliases) && false === $isReferenced) {
  62. $container->removeDefinition($id);
  63. $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'unused'));
  64. $hasChanged = true;
  65. }
  66. }
  67. if ($hasChanged) {
  68. $this->repeatedPass->setRepeat();
  69. }
  70. }
  71. }