4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\DependencyInjection\Compiler;
14 use Symfony\Component\DependencyInjection\ContainerBuilder;
17 * Removes unused service definitions from the container.
19 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
21 class RemoveUnusedDefinitionsPass implements RepeatablePassInterface
23 private $repeatedPass;
28 public function setRepeatedPass(RepeatedPass $repeatedPass)
30 $this->repeatedPass = $repeatedPass;
34 * Processes the ContainerBuilder to remove unused definitions.
36 * @param ContainerBuilder $container
38 public function process(ContainerBuilder $container)
40 $compiler = $container->getCompiler();
41 $formatter = $compiler->getLoggingFormatter();
42 $graph = $compiler->getServiceReferenceGraph();
45 foreach ($container->getDefinitions() as $id => $definition) {
46 if ($definition->isPublic()) {
50 if ($graph->hasNode($id)) {
51 $edges = $graph->getNode($id)->getInEdges();
52 $referencingAliases = array();
54 foreach ($edges as $edge) {
55 $node = $edge->getSourceNode();
56 $sourceIds[] = $node->getId();
58 if ($node->isAlias()) {
59 $referencingAliases[] = $node->getValue();
62 $isReferenced = (count(array_unique($sourceIds)) - count($referencingAliases)) > 0;
64 $referencingAliases = array();
65 $isReferenced = false;
68 if (1 === count($referencingAliases) && false === $isReferenced) {
69 $container->setDefinition((string) reset($referencingAliases), $definition);
70 $definition->setPublic(true);
71 $container->removeDefinition($id);
72 $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'replaces alias '.reset($referencingAliases)));
73 } elseif (0 === count($referencingAliases) && false === $isReferenced) {
74 $container->removeDefinition($id);
75 $container->resolveEnvPlaceholders(serialize($definition));
76 $compiler->addLogMessage($formatter->formatRemoveService($this, $id, 'unused'));
82 $this->repeatedPass->setRepeat();