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\Config\AutowireServiceResource;
15 use Symfony\Component\DependencyInjection\ContainerBuilder;
16 use Symfony\Component\DependencyInjection\Definition;
17 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
18 use Symfony\Component\DependencyInjection\Reference;
21 * Guesses constructor arguments of services definitions and try to instantiate services if necessary.
23 * @author Kévin Dunglas <dunglas@gmail.com>
25 class AutowirePass implements CompilerPassInterface
28 private $reflectionClasses = array();
29 private $definedTypes = array();
31 private $ambiguousServiceTypes = array();
32 private $autowired = array();
37 public function process(ContainerBuilder $container)
39 $throwingAutoloader = function ($class) { throw new \ReflectionException(sprintf('Class %s does not exist', $class)); };
40 spl_autoload_register($throwingAutoloader);
43 $this->container = $container;
44 foreach ($container->getDefinitions() as $id => $definition) {
45 if ($definition->isAutowired()) {
46 $this->completeDefinition($id, $definition);
50 spl_autoload_unregister($throwingAutoloader);
52 // Free memory and remove circular reference to container
53 $this->reflectionClasses = array();
54 $this->definedTypes = array();
56 $this->ambiguousServiceTypes = array();
57 $this->autowired = array();
62 * Creates a resource to help know if this service has changed.
64 * @param \ReflectionClass $reflectionClass
66 * @return AutowireServiceResource
68 public static function createResourceForClass(\ReflectionClass $reflectionClass)
72 if ($constructor = $reflectionClass->getConstructor()) {
73 $metadata['__construct'] = self::getResourceMetadataForMethod($constructor);
76 foreach (self::getSetters($reflectionClass) as $reflectionMethod) {
77 $metadata[$reflectionMethod->name] = self::getResourceMetadataForMethod($reflectionMethod);
80 return new AutowireServiceResource($reflectionClass->name, $reflectionClass->getFileName(), $metadata);
84 * Wires the given definition.
87 * @param Definition $definition
89 * @throws RuntimeException
91 private function completeDefinition($id, Definition $definition)
93 if ($definition->getFactory()) {
94 throw new RuntimeException(sprintf('Service "%s" can use either autowiring or a factory, not both.', $id));
97 if (!$reflectionClass = $this->getReflectionClass($id, $definition)) {
101 if ($this->container->isTrackingResources()) {
102 $this->container->addResource(static::createResourceForClass($reflectionClass));
105 if (!$constructor = $reflectionClass->getConstructor()) {
108 $parameters = $constructor->getParameters();
109 if (method_exists('ReflectionMethod', 'isVariadic') && $constructor->isVariadic()) {
110 array_pop($parameters);
113 $arguments = $definition->getArguments();
114 foreach ($parameters as $index => $parameter) {
115 if (array_key_exists($index, $arguments) && '' !== $arguments[$index]) {
120 if (!$typeHint = $parameter->getClass()) {
121 if (isset($arguments[$index])) {
125 // no default value? Then fail
126 if (!$parameter->isOptional()) {
127 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));
130 // specifically pass the default value
131 $arguments[$index] = $parameter->getDefaultValue();
136 if (isset($this->autowired[$typeHint->name])) {
137 $arguments[$index] = $this->autowired[$typeHint->name] ? new Reference($this->autowired[$typeHint->name]) : null;
141 if (null === $this->types) {
142 $this->populateAvailableTypes();
145 if (isset($this->types[$typeHint->name])) {
146 $value = new Reference($this->types[$typeHint->name]);
149 $value = $this->createAutowiredDefinition($typeHint, $id);
150 } catch (RuntimeException $e) {
151 if ($parameter->isDefaultValueAvailable()) {
152 $value = $parameter->getDefaultValue();
153 } elseif ($parameter->allowsNull()) {
158 $this->autowired[$typeHint->name] = false;
161 } catch (\ReflectionException $e) {
162 // Typehint against a non-existing class
164 if (!$parameter->isDefaultValueAvailable()) {
165 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);
168 $value = $parameter->getDefaultValue();
171 $arguments[$index] = $value;
174 if ($parameters && !isset($arguments[++$index])) {
175 while (0 <= --$index) {
176 $parameter = $parameters[$index];
177 if (!$parameter->isDefaultValueAvailable() || $parameter->getDefaultValue() !== $arguments[$index]) {
180 unset($arguments[$index]);
184 // it's possible index 1 was set, then index 0, then 2, etc
185 // make sure that we re-order so they're injected as expected
187 $definition->setArguments($arguments);
191 * Populates the list of available types.
193 private function populateAvailableTypes()
195 $this->types = array();
197 foreach ($this->container->getDefinitions() as $id => $definition) {
198 $this->populateAvailableType($id, $definition);
203 * Populates the list of available types for a given definition.
206 * @param Definition $definition
208 private function populateAvailableType($id, Definition $definition)
210 // Never use abstract services
211 if ($definition->isAbstract()) {
215 foreach ($definition->getAutowiringTypes() as $type) {
216 $this->definedTypes[$type] = true;
217 $this->types[$type] = $id;
218 unset($this->ambiguousServiceTypes[$type]);
221 if (!$reflectionClass = $this->getReflectionClass($id, $definition)) {
225 foreach ($reflectionClass->getInterfaces() as $reflectionInterface) {
226 $this->set($reflectionInterface->name, $id);
230 $this->set($reflectionClass->name, $id);
231 } while ($reflectionClass = $reflectionClass->getParentClass());
235 * Associates a type and a service id if applicable.
237 * @param string $type
240 private function set($type, $id)
242 if (isset($this->definedTypes[$type])) {
246 // is this already a type/class that is known to match multiple services?
247 if (isset($this->ambiguousServiceTypes[$type])) {
248 $this->ambiguousServiceTypes[$type][] = $id;
253 // check to make sure the type doesn't match multiple services
254 if (!isset($this->types[$type]) || $this->types[$type] === $id) {
255 $this->types[$type] = $id;
260 // keep an array of all services matching this type
261 if (!isset($this->ambiguousServiceTypes[$type])) {
262 $this->ambiguousServiceTypes[$type] = array($this->types[$type]);
263 unset($this->types[$type]);
265 $this->ambiguousServiceTypes[$type][] = $id;
269 * Registers a definition for the type if possible or throws an exception.
271 * @param \ReflectionClass $typeHint
274 * @return Reference A reference to the registered definition
276 * @throws RuntimeException
278 private function createAutowiredDefinition(\ReflectionClass $typeHint, $id)
280 if (isset($this->ambiguousServiceTypes[$typeHint->name])) {
281 $classOrInterface = $typeHint->isInterface() ? 'interface' : 'class';
282 $matchingServices = implode(', ', $this->ambiguousServiceTypes[$typeHint->name]);
284 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));
287 if (!$typeHint->isInstantiable()) {
288 $classOrInterface = $typeHint->isInterface() ? 'interface' : 'class';
289 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));
292 $this->autowired[$typeHint->name] = $argumentId = sprintf('autowired.%s', $typeHint->name);
294 $argumentDefinition = $this->container->register($argumentId, $typeHint->name);
295 $argumentDefinition->setPublic(false);
298 $this->completeDefinition($argumentId, $argumentDefinition);
299 } catch (RuntimeException $e) {
300 $classOrInterface = $typeHint->isInterface() ? 'interface' : 'class';
301 $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);
302 throw new RuntimeException($message, 0, $e);
305 return new Reference($argumentId);
309 * Retrieves the reflection class associated with the given service.
312 * @param Definition $definition
314 * @return \ReflectionClass|false
316 private function getReflectionClass($id, Definition $definition)
318 if (isset($this->reflectionClasses[$id])) {
319 return $this->reflectionClasses[$id];
322 // Cannot use reflection if the class isn't set
323 if (!$class = $definition->getClass()) {
327 $class = $this->container->getParameterBag()->resolveValue($class);
329 if ($deprecated = $definition->isDeprecated()) {
330 $prevErrorHandler = set_error_handler(function ($level, $message, $file, $line) use (&$prevErrorHandler) {
331 return (E_USER_DEPRECATED === $level || !$prevErrorHandler) ? false : $prevErrorHandler($level, $message, $file, $line);
338 $reflector = new \ReflectionClass($class);
339 } catch (\Exception $e) {
340 } catch (\Throwable $e) {
344 restore_error_handler();
348 if (!$e instanceof \ReflectionException) {
354 return $this->reflectionClasses[$id] = $reflector;
358 * @param \ReflectionClass $reflectionClass
360 * @return \ReflectionMethod[]
362 private static function getSetters(\ReflectionClass $reflectionClass)
364 foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
365 if (!$reflectionMethod->isStatic() && 1 === $reflectionMethod->getNumberOfParameters() && 0 === strpos($reflectionMethod->name, 'set')) {
366 yield $reflectionMethod;
371 private static function getResourceMetadataForMethod(\ReflectionMethod $method)
373 $methodArgumentsMetadata = array();
374 foreach ($method->getParameters() as $parameter) {
376 $class = $parameter->getClass();
377 } catch (\ReflectionException $e) {
378 // type-hint is against a non-existent class
382 $isVariadic = method_exists($parameter, 'isVariadic') && $parameter->isVariadic();
383 $methodArgumentsMetadata[] = array(
385 'isOptional' => $parameter->isOptional(),
386 'defaultValue' => ($parameter->isOptional() && !$isVariadic) ? $parameter->getDefaultValue() : null,
390 return $methodArgumentsMetadata;