RemoveUnusedDefinitionsPass.php 2.6 KB

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