This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/DependencyInjection/Compiler/RemoveUnusedDefinitionsPass.php

87 lines
2.8 KiB
PHP
Raw Normal View History

2010-12-29 19:12:24 +00:00
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
2010-12-29 19:12:24 +00:00
namespace Symfony\Component\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
2011-01-05 11:13:27 +00:00
* Removes unused service definitions from the container.
2010-12-29 19:12:24 +00:00
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class RemoveUnusedDefinitionsPass implements RepeatablePassInterface
2010-12-29 19:12:24 +00:00
{
private $repeatedPass;
2011-02-13 18:06:41 +00:00
/**
* {@inheritdoc}
2011-02-13 18:06:41 +00:00
*/
public function setRepeatedPass(RepeatedPass $repeatedPass)
{
$this->repeatedPass = $repeatedPass;
}
2011-02-13 18:06:41 +00:00
/**
* Processes the ContainerBuilder to remove unused definitions.
*
2011-04-12 23:51:22 +01:00
* @param ContainerBuilder $container
2011-02-13 18:06:41 +00:00
*/
2010-12-29 19:12:24 +00:00
public function process(ContainerBuilder $container)
{
2017-04-11 16:15:30 +01:00
$graph = $container->getCompiler()->getServiceReferenceGraph();
2010-12-29 19:12:24 +00:00
$hasChanged = false;
foreach ($container->getDefinitions() as $id => $definition) {
if ($definition->isPublic()) {
continue;
}
2011-01-17 22:28:59 +00:00
if ($graph->hasNode($id)) {
$edges = $graph->getNode($id)->getInEdges();
$referencingAliases = array();
$sourceIds = array();
foreach ($edges as $edge) {
if ($edge->isWeak()) {
continue;
}
$node = $edge->getSourceNode();
$sourceIds[] = $node->getId();
if ($node->isAlias()) {
$referencingAliases[] = $node->getValue();
}
}
$isReferenced = (count(array_unique($sourceIds)) - count($referencingAliases)) > 0;
} else {
$referencingAliases = array();
$isReferenced = false;
}
2011-01-05 11:13:27 +00:00
if (1 === count($referencingAliases) && false === $isReferenced) {
$container->setDefinition((string) reset($referencingAliases), $definition);
2011-01-05 11:13:27 +00:00
$definition->setPublic(true);
$container->removeDefinition($id);
$container->log($this, sprintf('Removed service "%s"; reason: replaces alias %s.', $id, reset($referencingAliases)));
2011-12-18 13:42:59 +00:00
} elseif (0 === count($referencingAliases) && false === $isReferenced) {
$container->removeDefinition($id);
$container->resolveEnvPlaceholders(serialize($definition));
$container->log($this, sprintf('Removed service "%s"; reason: unused.', $id));
2010-12-29 19:12:24 +00:00
$hasChanged = true;
}
}
if ($hasChanged) {
$this->repeatedPass->setRepeat();
2010-12-29 19:12:24 +00:00
}
}
2011-06-08 11:16:48 +01:00
}