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\Config\Resource\ClassExistenceResource;
15 use Symfony\Component\DependencyInjection\Config\AutowireServiceResource;
16 use Symfony\Component\DependencyInjection\ContainerBuilder;
17 use Symfony\Component\DependencyInjection\Definition;
18 use Symfony\Component\DependencyInjection\Exception\AutowiringFailedException;
19 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
20 use Symfony\Component\DependencyInjection\LazyProxy\ProxyHelper;
21 use Symfony\Component\DependencyInjection\TypedReference;
24 * Inspects existing service definitions and wires the autowired ones using the type hints of their classes.
26 * @author Kévin Dunglas <dunglas@gmail.com>
27 * @author Nicolas Grekas <p@tchwork.com>
29 class AutowirePass extends AbstractRecursivePass
31 private $definedTypes = array();
33 private $ambiguousServiceTypes;
34 private $autowired = array();
36 private $throwOnAutowiringException;
37 private $autowiringExceptions = array();
41 * @param bool $throwOnAutowireException Errors can be retrieved via Definition::getErrors()
43 public function __construct($throwOnAutowireException = true)
45 $this->throwOnAutowiringException = $throwOnAutowireException;
49 * @deprecated since version 3.4, to be removed in 4.0.
51 * @return AutowiringFailedException[]
53 public function getAutowiringExceptions()
55 @trigger_error('Calling AutowirePass::getAutowiringExceptions() is deprecated since Symfony 3.4 and will be removed in 4.0. Use Definition::getErrors() instead.', E_USER_DEPRECATED);
57 return $this->autowiringExceptions;
63 public function process(ContainerBuilder $container)
65 // clear out any possibly stored exceptions from before
66 $this->autowiringExceptions = array();
67 $this->strictMode = $container->hasParameter('container.autowiring.strict_mode') && $container->getParameter('container.autowiring.strict_mode');
70 parent::process($container);
72 $this->definedTypes = array();
74 $this->ambiguousServiceTypes = null;
75 $this->autowired = array();
80 * Creates a resource to help know if this service has changed.
82 * @param \ReflectionClass $reflectionClass
84 * @return AutowireServiceResource
86 * @deprecated since version 3.3, to be removed in 4.0. Use ContainerBuilder::getReflectionClass() instead.
88 public static function createResourceForClass(\ReflectionClass $reflectionClass)
90 @trigger_error('The '.__METHOD__.'() method is deprecated since Symfony 3.3 and will be removed in 4.0. Use ContainerBuilder::getReflectionClass() instead.', E_USER_DEPRECATED);
94 foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
95 if (!$reflectionMethod->isStatic()) {
96 $metadata[$reflectionMethod->name] = self::getResourceMetadataForMethod($reflectionMethod);
100 return new AutowireServiceResource($reflectionClass->name, $reflectionClass->getFileName(), $metadata);
106 protected function processValue($value, $isRoot = false)
109 return $this->doProcessValue($value, $isRoot);
110 } catch (AutowiringFailedException $e) {
111 if ($this->throwOnAutowiringException) {
115 $this->autowiringExceptions[] = $e;
116 $this->container->getDefinition($this->currentId)->addError($e->getMessage());
118 return parent::processValue($value, $isRoot);
122 private function doProcessValue($value, $isRoot = false)
124 if ($value instanceof TypedReference) {
125 if ($ref = $this->getAutowiredReference($value, $value->getRequiringClass() ? sprintf('for "%s" in "%s"', $value->getType(), $value->getRequiringClass()) : '')) {
128 $this->container->log($this, $this->createTypeNotFoundMessage($value, 'it'));
130 $value = parent::processValue($value, $isRoot);
132 if (!$value instanceof Definition || !$value->isAutowired() || $value->isAbstract() || !$value->getClass()) {
135 if (!$reflectionClass = $this->container->getReflectionClass($value->getClass(), false)) {
136 $this->container->log($this, sprintf('Skipping service "%s": Class or interface "%s" cannot be loaded.', $this->currentId, $value->getClass()));
141 $methodCalls = $value->getMethodCalls();
144 $constructor = $this->getConstructor($value, false);
145 } catch (RuntimeException $e) {
146 throw new AutowiringFailedException($this->currentId, $e->getMessage(), 0, $e);
150 array_unshift($methodCalls, array($constructor, $value->getArguments()));
153 $methodCalls = $this->autowireCalls($reflectionClass, $methodCalls);
156 list(, $arguments) = array_shift($methodCalls);
158 if ($arguments !== $value->getArguments()) {
159 $value->setArguments($arguments);
163 if ($methodCalls !== $value->getMethodCalls()) {
164 $value->setMethodCalls($methodCalls);
171 * @param \ReflectionClass $reflectionClass
172 * @param array $methodCalls
176 private function autowireCalls(\ReflectionClass $reflectionClass, array $methodCalls)
178 foreach ($methodCalls as $i => $call) {
179 list($method, $arguments) = $call;
181 if ($method instanceof \ReflectionFunctionAbstract) {
182 $reflectionMethod = $method;
184 $reflectionMethod = $this->getReflectionMethod(new Definition($reflectionClass->name), $method);
187 $arguments = $this->autowireMethod($reflectionMethod, $arguments);
189 if ($arguments !== $call[1]) {
190 $methodCalls[$i][1] = $arguments;
198 * Autowires the constructor or a method.
200 * @param \ReflectionFunctionAbstract $reflectionMethod
201 * @param array $arguments
203 * @return array The autowired arguments
205 * @throws AutowiringFailedException
207 private function autowireMethod(\ReflectionFunctionAbstract $reflectionMethod, array $arguments)
209 $class = $reflectionMethod instanceof \ReflectionMethod ? $reflectionMethod->class : $this->currentId;
210 $method = $reflectionMethod->name;
211 $parameters = $reflectionMethod->getParameters();
212 if (method_exists('ReflectionMethod', 'isVariadic') && $reflectionMethod->isVariadic()) {
213 array_pop($parameters);
216 foreach ($parameters as $index => $parameter) {
217 if (array_key_exists($index, $arguments) && '' !== $arguments[$index]) {
221 $type = ProxyHelper::getTypeHint($reflectionMethod, $parameter, true);
224 if (isset($arguments[$index])) {
228 // no default value? Then fail
229 if (!$parameter->isDefaultValueAvailable()) {
230 // For core classes, isDefaultValueAvailable() can
231 // be false when isOptional() returns true. If the
232 // argument *is* optional, allow it to be missing
233 if ($parameter->isOptional()) {
236 $type = ProxyHelper::getTypeHint($reflectionMethod, $parameter, false);
237 $type = $type ? sprintf('is type-hinted "%s"', $type) : 'has no type-hint';
239 throw new AutowiringFailedException($this->currentId, sprintf('Cannot autowire service "%s": argument "$%s" of method "%s()" %s, you should configure its value explicitly.', $this->currentId, $parameter->name, $class !== $this->currentId ? $class.'::'.$method : $method, $type));
242 // specifically pass the default value
243 $arguments[$index] = $parameter->getDefaultValue();
248 if (!$value = $this->getAutowiredReference($ref = new TypedReference($type, $type, !$parameter->isOptional() ? $class : ''), 'for '.sprintf('argument "$%s" of method "%s()"', $parameter->name, $class.'::'.$method))) {
249 $failureMessage = $this->createTypeNotFoundMessage($ref, sprintf('argument "$%s" of method "%s()"', $parameter->name, $class !== $this->currentId ? $class.'::'.$method : $method));
251 if ($parameter->isDefaultValueAvailable()) {
252 $value = $parameter->getDefaultValue();
253 } elseif (!$parameter->allowsNull()) {
254 throw new AutowiringFailedException($this->currentId, $failureMessage);
256 $this->container->log($this, $failureMessage);
259 $arguments[$index] = $value;
262 if ($parameters && !isset($arguments[++$index])) {
263 while (0 <= --$index) {
264 $parameter = $parameters[$index];
265 if (!$parameter->isDefaultValueAvailable() || $parameter->getDefaultValue() !== $arguments[$index]) {
268 unset($arguments[$index]);
272 // it's possible index 1 was set, then index 0, then 2, etc
273 // make sure that we re-order so they're injected as expected
280 * @return TypedReference|null A reference to the service matching the given type, if any
282 private function getAutowiredReference(TypedReference $reference, $deprecationMessage)
284 $this->lastFailure = null;
285 $type = $reference->getType();
287 if ($type !== $this->container->normalizeId($reference) || ($this->container->has($type) && !$this->container->findDefinition($type)->isAbstract())) {
291 if (null === $this->types) {
292 $this->populateAvailableTypes($this->strictMode);
295 if (isset($this->definedTypes[$type])) {
296 return new TypedReference($this->types[$type], $type);
299 if (!$this->strictMode && isset($this->types[$type])) {
300 $message = 'Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won\'t be supported in version 4.0.';
301 if ($aliasSuggestion = $this->getAliasesSuggestionForType($type = $reference->getType(), $deprecationMessage)) {
302 $message .= ' '.$aliasSuggestion;
304 $message .= sprintf(' You should %s the "%s" service to "%s" instead.', isset($this->types[$this->types[$type]]) ? 'alias' : 'rename (or alias)', $this->types[$type], $type);
307 @trigger_error($message, E_USER_DEPRECATED);
309 return new TypedReference($this->types[$type], $type);
312 if (!$reference->canBeAutoregistered() || isset($this->types[$type]) || isset($this->ambiguousServiceTypes[$type])) {
316 if (isset($this->autowired[$type])) {
317 return $this->autowired[$type] ? new TypedReference($this->autowired[$type], $type) : null;
320 if (!$this->strictMode) {
321 return $this->createAutowiredDefinition($type);
326 * Populates the list of available types.
328 private function populateAvailableTypes($onlyAutowiringTypes = false)
330 $this->types = array();
331 if (!$onlyAutowiringTypes) {
332 $this->ambiguousServiceTypes = array();
335 foreach ($this->container->getDefinitions() as $id => $definition) {
336 $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
341 * Populates the list of available types for a given definition.
344 * @param Definition $definition
346 private function populateAvailableType($id, Definition $definition, $onlyAutowiringTypes)
348 // Never use abstract services
349 if ($definition->isAbstract()) {
353 foreach ($definition->getAutowiringTypes(false) as $type) {
354 $this->definedTypes[$type] = true;
355 $this->types[$type] = $id;
356 unset($this->ambiguousServiceTypes[$type]);
359 if ($onlyAutowiringTypes) {
363 if (preg_match('/^\d+_[^~]++~[._a-zA-Z\d]{7}$/', $id) || $definition->isDeprecated() || !$reflectionClass = $this->container->getReflectionClass($definition->getClass(), false)) {
367 foreach ($reflectionClass->getInterfaces() as $reflectionInterface) {
368 $this->set($reflectionInterface->name, $id);
372 $this->set($reflectionClass->name, $id);
373 } while ($reflectionClass = $reflectionClass->getParentClass());
377 * Associates a type and a service id if applicable.
379 * @param string $type
382 private function set($type, $id)
384 if (isset($this->definedTypes[$type])) {
388 // is this already a type/class that is known to match multiple services?
389 if (isset($this->ambiguousServiceTypes[$type])) {
390 $this->ambiguousServiceTypes[$type][] = $id;
395 // check to make sure the type doesn't match multiple services
396 if (!isset($this->types[$type]) || $this->types[$type] === $id) {
397 $this->types[$type] = $id;
402 // keep an array of all services matching this type
403 if (!isset($this->ambiguousServiceTypes[$type])) {
404 $this->ambiguousServiceTypes[$type] = array($this->types[$type]);
405 unset($this->types[$type]);
407 $this->ambiguousServiceTypes[$type][] = $id;
411 * Registers a definition for the type if possible or throws an exception.
413 * @param string $type
415 * @return TypedReference|null A reference to the registered definition
417 private function createAutowiredDefinition($type)
419 if (!($typeHint = $this->container->getReflectionClass($type, false)) || !$typeHint->isInstantiable()) {
423 $currentId = $this->currentId;
424 $this->currentId = $type;
425 $this->autowired[$type] = $argumentId = sprintf('autowired.%s', $type);
426 $argumentDefinition = new Definition($type);
427 $argumentDefinition->setPublic(false);
428 $argumentDefinition->setAutowired(true);
431 $originalThrowSetting = $this->throwOnAutowiringException;
432 $this->throwOnAutowiringException = true;
433 $this->processValue($argumentDefinition, true);
434 $this->container->setDefinition($argumentId, $argumentDefinition);
435 } catch (AutowiringFailedException $e) {
436 $this->autowired[$type] = false;
437 $this->lastFailure = $e->getMessage();
438 $this->container->log($this, $this->lastFailure);
442 $this->throwOnAutowiringException = $originalThrowSetting;
443 $this->currentId = $currentId;
446 @trigger_error(sprintf('Relying on service auto-registration for type "%s" is deprecated since Symfony 3.4 and won\'t be supported in 4.0. Create a service named "%s" instead.', $type, $type), E_USER_DEPRECATED);
448 $this->container->log($this, sprintf('Type "%s" has been auto-registered for service "%s".', $type, $this->currentId));
450 return new TypedReference($argumentId, $type);
453 private function createTypeNotFoundMessage(TypedReference $reference, $label)
455 if (!$r = $this->container->getReflectionClass($type = $reference->getType(), false)) {
456 // either $type does not exist or a parent class does not exist
458 $resource = new ClassExistenceResource($type, false);
459 // isFresh() will explode ONLY if a parent class/trait does not exist
460 $resource->isFresh(0);
462 } catch (\ReflectionException $e) {
463 $parentMsg = $e->getMessage();
466 $message = sprintf('has type "%s" but this class %s.', $type, $parentMsg ? sprintf('is missing a parent class (%s)', $parentMsg) : 'was not found');
468 $alternatives = $this->createTypeAlternatives($reference);
469 $message = $this->container->has($type) ? 'this service is abstract' : 'no such service exists';
470 $message = sprintf('references %s "%s" but %s.%s', $r->isInterface() ? 'interface' : 'class', $type, $message, $alternatives);
472 if ($r->isInterface() && !$alternatives) {
473 $message .= ' Did you create a class that implements this interface?';
477 $message = sprintf('Cannot autowire service "%s": %s %s', $this->currentId, $label, $message);
479 if (null !== $this->lastFailure) {
480 $message = $this->lastFailure."\n".$message;
481 $this->lastFailure = null;
487 private function createTypeAlternatives(TypedReference $reference)
489 // try suggesting available aliases first
490 if ($message = $this->getAliasesSuggestionForType($type = $reference->getType())) {
493 if (null === $this->ambiguousServiceTypes) {
494 $this->populateAvailableTypes();
497 if (isset($this->ambiguousServiceTypes[$type])) {
498 $message = sprintf('one of these existing services: "%s"', implode('", "', $this->ambiguousServiceTypes[$type]));
499 } elseif (isset($this->types[$type])) {
500 $message = sprintf('the existing "%s" service', $this->types[$type]);
501 } elseif ($reference->getRequiringClass() && !$reference->canBeAutoregistered() && !$this->strictMode) {
502 return ' It cannot be auto-registered because it is from a different root namespace.';
507 return sprintf(' You should maybe alias this %s to %s.', class_exists($type, false) ? 'class' : 'interface', $message);
511 * @deprecated since version 3.3, to be removed in 4.0.
513 private static function getResourceMetadataForMethod(\ReflectionMethod $method)
515 $methodArgumentsMetadata = array();
516 foreach ($method->getParameters() as $parameter) {
518 $class = $parameter->getClass();
519 } catch (\ReflectionException $e) {
520 // type-hint is against a non-existent class
524 $isVariadic = method_exists($parameter, 'isVariadic') && $parameter->isVariadic();
525 $methodArgumentsMetadata[] = array(
527 'isOptional' => $parameter->isOptional(),
528 'defaultValue' => ($parameter->isOptional() && !$isVariadic) ? $parameter->getDefaultValue() : null,
532 return $methodArgumentsMetadata;
535 private function getAliasesSuggestionForType($type, $extraContext = null)
538 foreach (class_parents($type) + class_implements($type) as $parent) {
539 if ($this->container->has($parent) && !$this->container->findDefinition($parent)->isAbstract()) {
540 $aliases[] = $parent;
544 $extraContext = $extraContext ? ' '.$extraContext : '';
545 if (1 < $len = count($aliases)) {
546 $message = sprintf('Try changing the type-hint%s to one of its parents: ', $extraContext);
547 for ($i = 0, --$len; $i < $len; ++$i) {
548 $message .= sprintf('%s "%s", ', class_exists($aliases[$i], false) ? 'class' : 'interface', $aliases[$i]);
550 $message .= sprintf('or %s "%s".', class_exists($aliases[$i], false) ? 'class' : 'interface', $aliases[$i]);
556 return sprintf('Try changing the type-hint%s to "%s" instead.', $extraContext, $aliases[0]);