vendor/symfony/dependency-injection/Compiler/AutowirePass.php line 329

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\DependencyInjection\Compiler;
  11. use Symfony\Component\Config\Resource\ClassExistenceResource;
  12. use Symfony\Component\DependencyInjection\Config\AutowireServiceResource;
  13. use Symfony\Component\DependencyInjection\ContainerBuilder;
  14. use Symfony\Component\DependencyInjection\Definition;
  15. use Symfony\Component\DependencyInjection\Exception\AutowiringFailedException;
  16. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  17. use Symfony\Component\DependencyInjection\LazyProxy\ProxyHelper;
  18. use Symfony\Component\DependencyInjection\TypedReference;
  19. /**
  20.  * Inspects existing service definitions and wires the autowired ones using the type hints of their classes.
  21.  *
  22.  * @author Kévin Dunglas <dunglas@gmail.com>
  23.  * @author Nicolas Grekas <p@tchwork.com>
  24.  */
  25. class AutowirePass extends AbstractRecursivePass
  26. {
  27.     private $definedTypes = [];
  28.     private $types;
  29.     private $ambiguousServiceTypes;
  30.     private $autowired = [];
  31.     private $lastFailure;
  32.     private $throwOnAutowiringException;
  33.     private $autowiringExceptions = [];
  34.     private $strictMode;
  35.     /**
  36.      * @param bool $throwOnAutowireException Errors can be retrieved via Definition::getErrors()
  37.      */
  38.     public function __construct($throwOnAutowireException true)
  39.     {
  40.         $this->throwOnAutowiringException $throwOnAutowireException;
  41.     }
  42.     /**
  43.      * @deprecated since version 3.4, to be removed in 4.0.
  44.      *
  45.      * @return AutowiringFailedException[]
  46.      */
  47.     public function getAutowiringExceptions()
  48.     {
  49.         @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);
  50.         return $this->autowiringExceptions;
  51.     }
  52.     /**
  53.      * {@inheritdoc}
  54.      */
  55.     public function process(ContainerBuilder $container)
  56.     {
  57.         // clear out any possibly stored exceptions from before
  58.         $this->autowiringExceptions = [];
  59.         $this->strictMode $container->hasParameter('container.autowiring.strict_mode') && $container->getParameter('container.autowiring.strict_mode');
  60.         try {
  61.             parent::process($container);
  62.         } finally {
  63.             $this->definedTypes = [];
  64.             $this->types null;
  65.             $this->ambiguousServiceTypes null;
  66.             $this->autowired = [];
  67.         }
  68.     }
  69.     /**
  70.      * Creates a resource to help know if this service has changed.
  71.      *
  72.      * @param \ReflectionClass $reflectionClass
  73.      *
  74.      * @return AutowireServiceResource
  75.      *
  76.      * @deprecated since version 3.3, to be removed in 4.0. Use ContainerBuilder::getReflectionClass() instead.
  77.      */
  78.     public static function createResourceForClass(\ReflectionClass $reflectionClass)
  79.     {
  80.         @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);
  81.         $metadata = [];
  82.         foreach ($reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
  83.             if (!$reflectionMethod->isStatic()) {
  84.                 $metadata[$reflectionMethod->name] = self::getResourceMetadataForMethod($reflectionMethod);
  85.             }
  86.         }
  87.         return new AutowireServiceResource($reflectionClass->name$reflectionClass->getFileName(), $metadata);
  88.     }
  89.     /**
  90.      * {@inheritdoc}
  91.      */
  92.     protected function processValue($value$isRoot false)
  93.     {
  94.         try {
  95.             return $this->doProcessValue($value$isRoot);
  96.         } catch (AutowiringFailedException $e) {
  97.             if ($this->throwOnAutowiringException) {
  98.                 throw $e;
  99.             }
  100.             $this->autowiringExceptions[] = $e;
  101.             $this->container->getDefinition($this->currentId)->addError($e->getMessage());
  102.             return parent::processValue($value$isRoot);
  103.         }
  104.     }
  105.     private function doProcessValue($value$isRoot false)
  106.     {
  107.         if ($value instanceof TypedReference) {
  108.             if ($ref $this->getAutowiredReference($value$value->getRequiringClass() ? sprintf('for "%s" in "%s"'$value->getType(), $value->getRequiringClass()) : '')) {
  109.                 return $ref;
  110.             }
  111.             $this->container->log($this$this->createTypeNotFoundMessage($value'it'));
  112.         }
  113.         $value parent::processValue($value$isRoot);
  114.         if (!$value instanceof Definition || !$value->isAutowired() || $value->isAbstract() || !$value->getClass()) {
  115.             return $value;
  116.         }
  117.         if (!$reflectionClass $this->container->getReflectionClass($value->getClass(), false)) {
  118.             $this->container->log($thissprintf('Skipping service "%s": Class or interface "%s" cannot be loaded.'$this->currentId$value->getClass()));
  119.             return $value;
  120.         }
  121.         $methodCalls $value->getMethodCalls();
  122.         try {
  123.             $constructor $this->getConstructor($valuefalse);
  124.         } catch (RuntimeException $e) {
  125.             throw new AutowiringFailedException($this->currentId$e->getMessage(), 0$e);
  126.         }
  127.         if ($constructor) {
  128.             array_unshift($methodCalls, [$constructor$value->getArguments()]);
  129.         }
  130.         $methodCalls $this->autowireCalls($reflectionClass$methodCalls);
  131.         if ($constructor) {
  132.             list(, $arguments) = array_shift($methodCalls);
  133.             if ($arguments !== $value->getArguments()) {
  134.                 $value->setArguments($arguments);
  135.             }
  136.         }
  137.         if ($methodCalls !== $value->getMethodCalls()) {
  138.             $value->setMethodCalls($methodCalls);
  139.         }
  140.         return $value;
  141.     }
  142.     /**
  143.      * @param \ReflectionClass $reflectionClass
  144.      * @param array            $methodCalls
  145.      *
  146.      * @return array
  147.      */
  148.     private function autowireCalls(\ReflectionClass $reflectionClass, array $methodCalls)
  149.     {
  150.         foreach ($methodCalls as $i => $call) {
  151.             list($method$arguments) = $call;
  152.             if ($method instanceof \ReflectionFunctionAbstract) {
  153.                 $reflectionMethod $method;
  154.             } else {
  155.                 $definition = new Definition($reflectionClass->name);
  156.                 try {
  157.                     $reflectionMethod $this->getReflectionMethod($definition$method);
  158.                 } catch (RuntimeException $e) {
  159.                     if ($definition->getFactory()) {
  160.                         continue;
  161.                     }
  162.                     throw $e;
  163.                 }
  164.             }
  165.             $arguments $this->autowireMethod($reflectionMethod$arguments);
  166.             if ($arguments !== $call[1]) {
  167.                 $methodCalls[$i][1] = $arguments;
  168.             }
  169.         }
  170.         return $methodCalls;
  171.     }
  172.     /**
  173.      * Autowires the constructor or a method.
  174.      *
  175.      * @param \ReflectionFunctionAbstract $reflectionMethod
  176.      * @param array                       $arguments
  177.      *
  178.      * @return array The autowired arguments
  179.      *
  180.      * @throws AutowiringFailedException
  181.      */
  182.     private function autowireMethod(\ReflectionFunctionAbstract $reflectionMethod, array $arguments)
  183.     {
  184.         $class $reflectionMethod instanceof \ReflectionMethod $reflectionMethod->class $this->currentId;
  185.         $method $reflectionMethod->name;
  186.         $parameters $reflectionMethod->getParameters();
  187.         if (method_exists('ReflectionMethod''isVariadic') && $reflectionMethod->isVariadic()) {
  188.             array_pop($parameters);
  189.         }
  190.         foreach ($parameters as $index => $parameter) {
  191.             if (\array_key_exists($index$arguments) && '' !== $arguments[$index]) {
  192.                 continue;
  193.             }
  194.             $type ProxyHelper::getTypeHint($reflectionMethod$parametertrue);
  195.             if (!$type) {
  196.                 if (isset($arguments[$index])) {
  197.                     continue;
  198.                 }
  199.                 // no default value? Then fail
  200.                 if (!$parameter->isDefaultValueAvailable()) {
  201.                     // For core classes, isDefaultValueAvailable() can
  202.                     // be false when isOptional() returns true. If the
  203.                     // argument *is* optional, allow it to be missing
  204.                     if ($parameter->isOptional()) {
  205.                         continue;
  206.                     }
  207.                     $type ProxyHelper::getTypeHint($reflectionMethod$parameterfalse);
  208.                     $type $type sprintf('is type-hinted "%s"'$type) : 'has no type-hint';
  209.                     throw new AutowiringFailedException($this->currentIdsprintf('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));
  210.                 }
  211.                 // specifically pass the default value
  212.                 $arguments[$index] = $parameter->getDefaultValue();
  213.                 continue;
  214.             }
  215.             if (!$value $this->getAutowiredReference($ref = new TypedReference($type$type, !$parameter->isOptional() ? $class ''), 'for '.sprintf('argument "$%s" of method "%s()"'$parameter->name$class.'::'.$method))) {
  216.                 $failureMessage $this->createTypeNotFoundMessage($refsprintf('argument "$%s" of method "%s()"'$parameter->name$class !== $this->currentId $class.'::'.$method $method));
  217.                 if ($parameter->isDefaultValueAvailable()) {
  218.                     $value $parameter->getDefaultValue();
  219.                 } elseif (!$parameter->allowsNull()) {
  220.                     throw new AutowiringFailedException($this->currentId$failureMessage);
  221.                 }
  222.                 $this->container->log($this$failureMessage);
  223.             }
  224.             $arguments[$index] = $value;
  225.         }
  226.         if ($parameters && !isset($arguments[++$index])) {
  227.             while (<= --$index) {
  228.                 $parameter $parameters[$index];
  229.                 if (!$parameter->isDefaultValueAvailable() || $parameter->getDefaultValue() !== $arguments[$index]) {
  230.                     break;
  231.                 }
  232.                 unset($arguments[$index]);
  233.             }
  234.         }
  235.         // it's possible index 1 was set, then index 0, then 2, etc
  236.         // make sure that we re-order so they're injected as expected
  237.         ksort($arguments);
  238.         return $arguments;
  239.     }
  240.     /**
  241.      * @return TypedReference|null A reference to the service matching the given type, if any
  242.      */
  243.     private function getAutowiredReference(TypedReference $reference$deprecationMessage)
  244.     {
  245.         $this->lastFailure null;
  246.         $type $reference->getType();
  247.         if ($type !== $this->container->normalizeId($reference) || ($this->container->has($type) && !$this->container->findDefinition($type)->isAbstract())) {
  248.             return $reference;
  249.         }
  250.         if (null === $this->types) {
  251.             $this->populateAvailableTypes($this->strictMode);
  252.         }
  253.         if (isset($this->definedTypes[$type])) {
  254.             return new TypedReference($this->types[$type], $type);
  255.         }
  256.         if (!$this->strictMode && isset($this->types[$type])) {
  257.             $message 'Autowiring services based on the types they implement is deprecated since Symfony 3.3 and won\'t be supported in version 4.0.';
  258.             if ($aliasSuggestion $this->getAliasesSuggestionForType($type $reference->getType(), $deprecationMessage)) {
  259.                 $message .= ' '.$aliasSuggestion;
  260.             } else {
  261.                 $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);
  262.             }
  263.             @trigger_error($messageE_USER_DEPRECATED);
  264.             return new TypedReference($this->types[$type], $type);
  265.         }
  266.         if (!$reference->canBeAutoregistered() || isset($this->types[$type]) || isset($this->ambiguousServiceTypes[$type])) {
  267.             return;
  268.         }
  269.         if (isset($this->autowired[$type])) {
  270.             return $this->autowired[$type] ? new TypedReference($this->autowired[$type], $type) : null;
  271.         }
  272.         if (!$this->strictMode) {
  273.             return $this->createAutowiredDefinition($type);
  274.         }
  275.     }
  276.     /**
  277.      * Populates the list of available types.
  278.      */
  279.     private function populateAvailableTypes($onlyAutowiringTypes false)
  280.     {
  281.         $this->types = [];
  282.         if (!$onlyAutowiringTypes) {
  283.             $this->ambiguousServiceTypes = [];
  284.         }
  285.         foreach ($this->container->getDefinitions() as $id => $definition) {
  286.             $this->populateAvailableType($id$definition$onlyAutowiringTypes);
  287.         }
  288.     }
  289.     /**
  290.      * Populates the list of available types for a given definition.
  291.      *
  292.      * @param string     $id
  293.      * @param Definition $definition
  294.      */
  295.     private function populateAvailableType($idDefinition $definition$onlyAutowiringTypes)
  296.     {
  297.         // Never use abstract services
  298.         if ($definition->isAbstract()) {
  299.             return;
  300.         }
  301.         foreach ($definition->getAutowiringTypes(false) as $type) {
  302.             $this->definedTypes[$type] = true;
  303.             $this->types[$type] = $id;
  304.             unset($this->ambiguousServiceTypes[$type]);
  305.         }
  306.         if ($onlyAutowiringTypes) {
  307.             return;
  308.         }
  309.         if (preg_match('/^\d+_[^~]++~[._a-zA-Z\d]{7}$/'$id) || $definition->isDeprecated() || !$reflectionClass $this->container->getReflectionClass($definition->getClass(), false)) {
  310.             return;
  311.         }
  312.         foreach ($reflectionClass->getInterfaces() as $reflectionInterface) {
  313.             $this->set($reflectionInterface->name$id);
  314.         }
  315.         do {
  316.             $this->set($reflectionClass->name$id);
  317.         } while ($reflectionClass $reflectionClass->getParentClass());
  318.     }
  319.     /**
  320.      * Associates a type and a service id if applicable.
  321.      *
  322.      * @param string $type
  323.      * @param string $id
  324.      */
  325.     private function set($type$id)
  326.     {
  327.         if (isset($this->definedTypes[$type])) {
  328.             return;
  329.         }
  330.         // is this already a type/class that is known to match multiple services?
  331.         if (isset($this->ambiguousServiceTypes[$type])) {
  332.             $this->ambiguousServiceTypes[$type][] = $id;
  333.             return;
  334.         }
  335.         // check to make sure the type doesn't match multiple services
  336.         if (!isset($this->types[$type]) || $this->types[$type] === $id) {
  337.             $this->types[$type] = $id;
  338.             return;
  339.         }
  340.         // keep an array of all services matching this type
  341.         if (!isset($this->ambiguousServiceTypes[$type])) {
  342.             $this->ambiguousServiceTypes[$type] = [$this->types[$type]];
  343.             unset($this->types[$type]);
  344.         }
  345.         $this->ambiguousServiceTypes[$type][] = $id;
  346.     }
  347.     /**
  348.      * Registers a definition for the type if possible or throws an exception.
  349.      *
  350.      * @param string $type
  351.      *
  352.      * @return TypedReference|null A reference to the registered definition
  353.      */
  354.     private function createAutowiredDefinition($type)
  355.     {
  356.         if (!($typeHint $this->container->getReflectionClass($typefalse)) || !$typeHint->isInstantiable()) {
  357.             return;
  358.         }
  359.         $currentId $this->currentId;
  360.         $this->currentId $type;
  361.         $this->autowired[$type] = $argumentId sprintf('autowired.%s'$type);
  362.         $argumentDefinition = new Definition($type);
  363.         $argumentDefinition->setPublic(false);
  364.         $argumentDefinition->setAutowired(true);
  365.         try {
  366.             $originalThrowSetting $this->throwOnAutowiringException;
  367.             $this->throwOnAutowiringException true;
  368.             $this->processValue($argumentDefinitiontrue);
  369.             $this->container->setDefinition($argumentId$argumentDefinition);
  370.         } catch (AutowiringFailedException $e) {
  371.             $this->autowired[$type] = false;
  372.             $this->lastFailure $e->getMessage();
  373.             $this->container->log($this$this->lastFailure);
  374.             return;
  375.         } finally {
  376.             $this->throwOnAutowiringException $originalThrowSetting;
  377.             $this->currentId $currentId;
  378.         }
  379.         @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);
  380.         $this->container->log($thissprintf('Type "%s" has been auto-registered for service "%s".'$type$this->currentId));
  381.         return new TypedReference($argumentId$type);
  382.     }
  383.     private function createTypeNotFoundMessage(TypedReference $reference$label)
  384.     {
  385.         $trackResources $this->container->isTrackingResources();
  386.         $this->container->setResourceTracking(false);
  387.         try {
  388.             if ($r $this->container->getReflectionClass($type $reference->getType(), false)) {
  389.                 $alternatives $this->createTypeAlternatives($reference);
  390.             }
  391.         } finally {
  392.             $this->container->setResourceTracking($trackResources);
  393.         }
  394.         if (!$r) {
  395.             // either $type does not exist or a parent class does not exist
  396.             try {
  397.                 $resource = new ClassExistenceResource($typefalse);
  398.                 // isFresh() will explode ONLY if a parent class/trait does not exist
  399.                 $resource->isFresh(0);
  400.                 $parentMsg false;
  401.             } catch (\ReflectionException $e) {
  402.                 $parentMsg $e->getMessage();
  403.             }
  404.             $message sprintf('has type "%s" but this class %s.'$type$parentMsg sprintf('is missing a parent class (%s)'$parentMsg) : 'was not found');
  405.         } else {
  406.             $message $this->container->has($type) ? 'this service is abstract' 'no such service exists';
  407.             $message sprintf('references %s "%s" but %s.%s'$r->isInterface() ? 'interface' 'class'$type$message$alternatives);
  408.             if ($r->isInterface() && !$alternatives) {
  409.                 $message .= ' Did you create a class that implements this interface?';
  410.             }
  411.         }
  412.         $message sprintf('Cannot autowire service "%s": %s %s'$this->currentId$label$message);
  413.         if (null !== $this->lastFailure) {
  414.             $message $this->lastFailure."\n".$message;
  415.             $this->lastFailure null;
  416.         }
  417.         return $message;
  418.     }
  419.     private function createTypeAlternatives(TypedReference $reference)
  420.     {
  421.         // try suggesting available aliases first
  422.         if ($message $this->getAliasesSuggestionForType($type $reference->getType())) {
  423.             return ' '.$message;
  424.         }
  425.         if (null === $this->ambiguousServiceTypes) {
  426.             $this->populateAvailableTypes();
  427.         }
  428.         if (isset($this->ambiguousServiceTypes[$type])) {
  429.             $message sprintf('one of these existing services: "%s"'implode('", "'$this->ambiguousServiceTypes[$type]));
  430.         } elseif (isset($this->types[$type])) {
  431.             $message sprintf('the existing "%s" service'$this->types[$type]);
  432.         } elseif ($reference->getRequiringClass() && !$reference->canBeAutoregistered() && !$this->strictMode) {
  433.             return ' It cannot be auto-registered because it is from a different root namespace.';
  434.         } else {
  435.             return;
  436.         }
  437.         return sprintf(' You should maybe alias this %s to %s.'class_exists($typefalse) ? 'class' 'interface'$message);
  438.     }
  439.     /**
  440.      * @deprecated since version 3.3, to be removed in 4.0.
  441.      */
  442.     private static function getResourceMetadataForMethod(\ReflectionMethod $method)
  443.     {
  444.         $methodArgumentsMetadata = [];
  445.         foreach ($method->getParameters() as $parameter) {
  446.             try {
  447.                 $class $parameter->getClass();
  448.             } catch (\ReflectionException $e) {
  449.                 // type-hint is against a non-existent class
  450.                 $class false;
  451.             }
  452.             $isVariadic method_exists($parameter'isVariadic') && $parameter->isVariadic();
  453.             $methodArgumentsMetadata[] = [
  454.                 'class' => $class,
  455.                 'isOptional' => $parameter->isOptional(),
  456.                 'defaultValue' => ($parameter->isOptional() && !$isVariadic) ? $parameter->getDefaultValue() : null,
  457.             ];
  458.         }
  459.         return $methodArgumentsMetadata;
  460.     }
  461.     private function getAliasesSuggestionForType($type$extraContext null)
  462.     {
  463.         $aliases = [];
  464.         foreach (class_parents($type) + class_implements($type) as $parent) {
  465.             if ($this->container->has($parent) && !$this->container->findDefinition($parent)->isAbstract()) {
  466.                 $aliases[] = $parent;
  467.             }
  468.         }
  469.         $extraContext $extraContext ' '.$extraContext '';
  470.         if ($len = \count($aliases)) {
  471.             $message sprintf('Try changing the type-hint%s to one of its parents: '$extraContext);
  472.             for ($i 0, --$len$i $len; ++$i) {
  473.                 $message .= sprintf('%s "%s", 'class_exists($aliases[$i], false) ? 'class' 'interface'$aliases[$i]);
  474.             }
  475.             $message .= sprintf('or %s "%s".'class_exists($aliases[$i], false) ? 'class' 'interface'$aliases[$i]);
  476.             return $message;
  477.         }
  478.         if ($aliases) {
  479.             return sprintf('Try changing the type-hint%s to "%s" instead.'$extraContext$aliases[0]);
  480.         }
  481.     }
  482. }