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\Argument\ArgumentInterface;
15 use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
16 use Symfony\Component\DependencyInjection\ContainerBuilder;
17 use Symfony\Component\DependencyInjection\ContainerInterface;
18 use Symfony\Component\DependencyInjection\Definition;
19 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
20 use Symfony\Component\DependencyInjection\Reference;
23 * Emulates the invalid behavior if the reference is not found within the
26 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
28 class ResolveInvalidReferencesPass implements CompilerPassInterface
31 private $signalingException;
34 * Process the ContainerBuilder to resolve invalid references.
36 public function process(ContainerBuilder $container)
38 $this->container = $container;
39 $this->signalingException = new RuntimeException('Invalid reference.');
42 $this->processValue($container->getDefinitions(), 1);
44 $this->container = $this->signalingException = null;
49 * Processes arguments to determine invalid references.
51 * @throws RuntimeException When an invalid reference is found
53 private function processValue($value, $rootLevel = 0, $level = 0)
55 if ($value instanceof ServiceClosureArgument) {
56 $value->setValues($this->processValue($value->getValues(), 1, 1));
57 } elseif ($value instanceof ArgumentInterface) {
58 $value->setValues($this->processValue($value->getValues(), $rootLevel, 1 + $level));
59 } elseif ($value instanceof Definition) {
60 if ($value->isSynthetic() || $value->isAbstract()) {
63 $value->setArguments($this->processValue($value->getArguments(), 0));
64 $value->setProperties($this->processValue($value->getProperties(), 1));
65 $value->setMethodCalls($this->processValue($value->getMethodCalls(), 2));
66 } elseif (\is_array($value)) {
69 foreach ($value as $k => $v) {
71 if (false !== $i && $k !== $i++) {
74 if ($v !== $processedValue = $this->processValue($v, $rootLevel, 1 + $level)) {
75 $value[$k] = $processedValue;
77 } catch (RuntimeException $e) {
78 if ($rootLevel < $level || ($rootLevel && !$level)) {
80 } elseif ($rootLevel) {
88 // Ensure numerically indexed arguments have sequential numeric keys.
90 $value = array_values($value);
92 } elseif ($value instanceof Reference) {
93 if ($this->container->has($value)) {
96 $invalidBehavior = $value->getInvalidBehavior();
98 // resolve invalid behavior
99 if (ContainerInterface::NULL_ON_INVALID_REFERENCE === $invalidBehavior) {
101 } elseif (ContainerInterface::IGNORE_ON_INVALID_REFERENCE === $invalidBehavior) {
102 if (0 < $level || $rootLevel) {
103 throw $this->signalingException;