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/InlineServiceDefinitionsPass.php

95 lines
3.0 KiB
PHP
Raw Normal View History

2011-01-05 11:13:27 +00:00
<?php
namespace Symfony\Component\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/*
* 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.
*/
/**
* Inline service definitions where this is possible.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class InlineServiceDefinitionsPass implements RepeatablePassInterface
2011-01-05 11:13:27 +00:00
{
protected $repeatedPass;
protected $graph;
public function setRepeatedPass(RepeatedPass $repeatedPass)
{
$this->repeatedPass = $repeatedPass;
}
2011-01-07 14:44:29 +00:00
2011-01-05 11:13:27 +00:00
public function process(ContainerBuilder $container)
{
$this->graph = $this->repeatedPass->getCompiler()->getServiceReferenceGraph();
2011-01-07 14:44:29 +00:00
2011-01-05 11:13:27 +00:00
foreach ($container->getDefinitions() as $id => $definition) {
$definition->setArguments(
$this->inlineArguments($container, $definition->getArguments())
);
$definition->setMethodCalls(
$this->inlineArguments($container, $definition->getMethodCalls())
);
}
}
protected function inlineArguments(ContainerBuilder $container, array $arguments)
{
foreach ($arguments as $k => $argument) {
if (is_array($argument)) {
$arguments[$k] = $this->inlineArguments($container, $argument);
} else if ($argument instanceof Reference) {
if (!$container->hasDefinition($id = (string) $argument)) {
continue;
}
if ($this->isInlinableDefinition($container, $id, $definition = $container->getDefinition($id))) {
if ($definition->isShared()) {
$arguments[$k] = $definition;
} else {
$arguments[$k] = clone $definition;
}
2011-01-05 11:13:27 +00:00
}
} else if ($argument instanceof Definition) {
$argument->setArguments($this->inlineArguments($container, $argument->getArguments()));
$argument->setMethodCalls($this->inlineArguments($container, $argument->getMethodCalls()));
2011-01-05 11:13:27 +00:00
}
}
return $arguments;
}
protected function isInlinableDefinition(ContainerBuilder $container, $id, Definition $definition)
{
if (!$definition->isShared()) {
return true;
}
if ($definition->isPublic()) {
return false;
}
if (!$this->graph->hasNode($id)) {
return true;
2011-01-05 11:13:27 +00:00
}
$ids = array();
foreach ($this->graph->getNode($id)->getInEdges() as $edge) {
$ids[] = $edge->getSourceNode()->getId();
2011-01-05 11:13:27 +00:00
}
return count(array_unique($ids)) <= 1;
2011-01-05 11:13:27 +00:00
}
}