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

91 lines
2.7 KiB
PHP
Raw Normal View History

2010-12-29 19:12:24 +00:00
<?php
namespace Symfony\Component\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
2011-01-05 11:13:27 +00:00
/*
* This file is part of the Symfony framework.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
2010-12-29 19:12:24 +00:00
/**
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 CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$hasChanged = false;
$aliases = $container->getAliases();
foreach ($container->getDefinitions() as $id => $definition) {
if ($definition->isPublic()) {
continue;
}
2011-01-05 11:13:27 +00:00
$referencingAliases = array_keys($aliases, $id, true);
$isReferenced = $this->isReferenced($container, $id);
if (1 === count($referencingAliases) && false === $isReferenced) {
$container->setDefinition(reset($referencingAliases), $definition);
$definition->setPublic(true);
$container->remove($id);
} else if (0 === count($referencingAliases) && false === $isReferenced) {
2010-12-29 19:12:24 +00:00
$container->remove($id);
$hasChanged = true;
}
}
if ($hasChanged) {
$this->process($container);
}
}
protected function isReferenced(ContainerBuilder $container, $id)
{
foreach ($container->getDefinitions() as $definition) {
if ($this->isReferencedByArgument($id, $definition->getArguments())) {
return true;
}
2011-01-05 11:13:27 +00:00
if ($this->isReferencedByArgument($id, $definition->getMethodCalls())) {
return true;
2010-12-29 19:12:24 +00:00
}
}
return false;
}
protected function isReferencedByArgument($id, $argument)
{
if (is_array($argument)) {
foreach ($argument as $arg) {
if ($this->isReferencedByArgument($id, $arg)) {
return true;
}
}
} else if ($argument instanceof Reference) {
if ($id === (string) $argument) {
return true;
}
2011-01-05 11:13:27 +00:00
} else if ($argument instanceof Definition) {
if ($this->isReferencedByArgument($id, $argument->getArguments())) {
return true;
}
if ($this->isReferencedByArgument($id, $argument->getMethodCalls())) {
return true;
}
2010-12-29 19:12:24 +00:00
}
return false;
}
}