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;
15 use Symfony\Component\DependencyInjection\Definition;
16 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
17 use Symfony\Component\DependencyInjection\Reference;
20 * Guesses constructor arguments of services definitions and try to instantiate services if necessary.
22 * @author Kévin Dunglas <dunglas@gmail.com>
24 class AutowirePass implements CompilerPassInterface
27 private $reflectionClasses = array();
28 private $definedTypes = array();
30 private $notGuessableTypes = array();
31 private $autowired = array();
36 public function process(ContainerBuilder $container)
38 $throwingAutoloader = function ($class) { throw new \ReflectionException(sprintf('Class %s does not exist', $class)); };
39 spl_autoload_register($throwingAutoloader);
42 $this->container = $container;
43 foreach ($container->getDefinitions() as $id => $definition) {
44 if ($definition->isAutowired()) {
45 $this->completeDefinition($id, $definition);
48 } catch (\Exception $e) {
49 } catch (\Throwable $e) {
52 spl_autoload_unregister($throwingAutoloader);
54 // Free memory and remove circular reference to container
55 $this->container = null;
56 $this->reflectionClasses = array();
57 $this->definedTypes = array();
59 $this->notGuessableTypes = array();
60 $this->autowired = array();
68 * Wires the given definition.
71 * @param Definition $definition
73 * @throws RuntimeException
75 private function completeDefinition($id, Definition $definition)
77 if ($definition->getFactory() || $definition->getFactoryClass(false) || $definition->getFactoryService(false)) {
78 throw new RuntimeException(sprintf('Service "%s" can use either autowiring or a factory, not both.', $id));
81 if (!$reflectionClass = $this->getReflectionClass($id, $definition)) {
85 $this->container->addClassResource($reflectionClass);
87 if (!$constructor = $reflectionClass->getConstructor()) {
90 $parameters = $constructor->getParameters();
91 if (method_exists('ReflectionMethod', 'isVariadic') && $constructor->isVariadic()) {
92 array_pop($parameters);
95 $arguments = $definition->getArguments();
96 foreach ($parameters as $index => $parameter) {
97 if (array_key_exists($index, $arguments) && '' !== $arguments[$index]) {
102 if (!$typeHint = $parameter->getClass()) {
103 if (isset($arguments[$index])) {
107 // no default value? Then fail
108 if (!$parameter->isOptional()) {
109 throw new RuntimeException(sprintf('Unable to autowire argument index %d ($%s) for the service "%s". If this is an object, give it a type-hint. Otherwise, specify this argument\'s value explicitly.', $index, $parameter->name, $id));
112 // specifically pass the default value
113 $arguments[$index] = $parameter->getDefaultValue();
118 if (isset($this->autowired[$typeHint->name])) {
119 return $this->autowired[$typeHint->name] ? new Reference($this->autowired[$typeHint->name]) : null;
122 if (null === $this->types) {
123 $this->populateAvailableTypes();
126 if (isset($this->types[$typeHint->name]) && !isset($this->notGuessableTypes[$typeHint->name])) {
127 $value = new Reference($this->types[$typeHint->name]);
130 $value = $this->createAutowiredDefinition($typeHint, $id);
131 } catch (RuntimeException $e) {
132 if ($parameter->isDefaultValueAvailable()) {
133 $value = $parameter->getDefaultValue();
134 } elseif ($parameter->allowsNull()) {
139 $this->autowired[$typeHint->name] = false;
142 } catch (\ReflectionException $e) {
143 // Typehint against a non-existing class
145 if (!$parameter->isDefaultValueAvailable()) {
146 throw new RuntimeException(sprintf('Cannot autowire argument %s for %s because the type-hinted class does not exist (%s).', $index + 1, $definition->getClass(), $e->getMessage()), 0, $e);
149 $value = $parameter->getDefaultValue();
152 $arguments[$index] = $value;
155 if ($parameters && !isset($arguments[++$index])) {
156 while (0 <= --$index) {
157 $parameter = $parameters[$index];
158 if (!$parameter->isDefaultValueAvailable() || $parameter->getDefaultValue() !== $arguments[$index]) {
161 unset($arguments[$index]);
165 // it's possible index 1 was set, then index 0, then 2, etc
166 // make sure that we re-order so they're injected as expected
168 $definition->setArguments($arguments);
172 * Populates the list of available types.
174 private function populateAvailableTypes()
176 $this->types = array();
178 foreach ($this->container->getDefinitions() as $id => $definition) {
179 $this->populateAvailableType($id, $definition);
184 * Populates the list of available types for a given definition.
187 * @param Definition $definition
189 private function populateAvailableType($id, Definition $definition)
191 // Never use abstract services
192 if ($definition->isAbstract()) {
196 foreach ($definition->getAutowiringTypes() as $type) {
197 $this->definedTypes[$type] = true;
198 $this->types[$type] = $id;
199 unset($this->notGuessableTypes[$type]);
202 if (!$reflectionClass = $this->getReflectionClass($id, $definition)) {
206 foreach ($reflectionClass->getInterfaces() as $reflectionInterface) {
207 $this->set($reflectionInterface->name, $id);
211 $this->set($reflectionClass->name, $id);
212 } while ($reflectionClass = $reflectionClass->getParentClass());
216 * Associates a type and a service id if applicable.
218 * @param string $type
221 private function set($type, $id)
223 if (isset($this->definedTypes[$type])) {
227 if (!isset($this->types[$type])) {
228 $this->types[$type] = $id;
233 if ($this->types[$type] === $id) {
237 if (!isset($this->notGuessableTypes[$type])) {
238 $this->notGuessableTypes[$type] = true;
239 $this->types[$type] = (array) $this->types[$type];
242 $this->types[$type][] = $id;
246 * Registers a definition for the type if possible or throws an exception.
248 * @param \ReflectionClass $typeHint
251 * @return Reference A reference to the registered definition
253 * @throws RuntimeException
255 private function createAutowiredDefinition(\ReflectionClass $typeHint, $id)
257 if (isset($this->notGuessableTypes[$typeHint->name])) {
258 $classOrInterface = $typeHint->isInterface() ? 'interface' : 'class';
259 $matchingServices = implode(', ', $this->types[$typeHint->name]);
261 throw new RuntimeException(sprintf('Unable to autowire argument of type "%s" for the service "%s". Multiple services exist for this %s (%s).', $typeHint->name, $id, $classOrInterface, $matchingServices));
264 if (!$typeHint->isInstantiable()) {
265 $classOrInterface = $typeHint->isInterface() ? 'interface' : 'class';
266 throw new RuntimeException(sprintf('Unable to autowire argument of type "%s" for the service "%s". No services were found matching this %s and it cannot be auto-registered.', $typeHint->name, $id, $classOrInterface));
269 $this->autowired[$typeHint->name] = $argumentId = sprintf('autowired.%s', $typeHint->name);
271 $argumentDefinition = $this->container->register($argumentId, $typeHint->name);
272 $argumentDefinition->setPublic(false);
275 $this->completeDefinition($argumentId, $argumentDefinition);
276 } catch (RuntimeException $e) {
277 $classOrInterface = $typeHint->isInterface() ? 'interface' : 'class';
278 $message = sprintf('Unable to autowire argument of type "%s" for the service "%s". No services were found matching this %s and it cannot be auto-registered.', $typeHint->name, $id, $classOrInterface);
279 throw new RuntimeException($message, 0, $e);
282 return new Reference($argumentId);
286 * Retrieves the reflection class associated with the given service.
289 * @param Definition $definition
291 * @return \ReflectionClass|false
293 private function getReflectionClass($id, Definition $definition)
295 if (isset($this->reflectionClasses[$id])) {
296 return $this->reflectionClasses[$id];
299 // Cannot use reflection if the class isn't set
300 if (!$class = $definition->getClass()) {
304 $class = $this->container->getParameterBag()->resolveValue($class);
307 $reflector = new \ReflectionClass($class);
308 } catch (\ReflectionException $e) {
312 return $this->reflectionClasses[$id] = $reflector;