vendor/symfony/http-kernel/DependencyInjection/RegisterControllerArgumentLocatorsPass.php line 150

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\HttpKernel\DependencyInjection;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\DependencyInjection\Attribute\Autowire;
  13. use Symfony\Component\DependencyInjection\Attribute\Target;
  14. use Symfony\Component\DependencyInjection\ChildDefinition;
  15. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  16. use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
  17. use Symfony\Component\DependencyInjection\ContainerAwareInterface;
  18. use Symfony\Component\DependencyInjection\ContainerBuilder;
  19. use Symfony\Component\DependencyInjection\ContainerInterface;
  20. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  21. use Symfony\Component\DependencyInjection\LazyProxy\ProxyHelper;
  22. use Symfony\Component\DependencyInjection\Reference;
  23. use Symfony\Component\DependencyInjection\TypedReference;
  24. use Symfony\Component\HttpFoundation\Request;
  25. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  26. /**
  27.  * Creates the service-locators required by ServiceValueResolver.
  28.  *
  29.  * @author Nicolas Grekas <p@tchwork.com>
  30.  */
  31. class RegisterControllerArgumentLocatorsPass implements CompilerPassInterface
  32. {
  33.     public function process(ContainerBuilder $container)
  34.     {
  35.         if (!$container->hasDefinition('argument_resolver.service') && !$container->hasDefinition('argument_resolver.not_tagged_controller')) {
  36.             return;
  37.         }
  38.         $parameterBag $container->getParameterBag();
  39.         $controllers = [];
  40.         $publicAliases = [];
  41.         foreach ($container->getAliases() as $id => $alias) {
  42.             if ($alias->isPublic() && !$alias->isPrivate()) {
  43.                 $publicAliases[(string) $alias][] = $id;
  44.             }
  45.         }
  46.         $emptyAutowireAttributes class_exists(Autowire::class) ? null : [];
  47.         foreach ($container->findTaggedServiceIds('controller.service_arguments'true) as $id => $tags) {
  48.             $def $container->getDefinition($id);
  49.             $def->setPublic(true);
  50.             $class $def->getClass();
  51.             $autowire $def->isAutowired();
  52.             $bindings $def->getBindings();
  53.             // resolve service class, taking parent definitions into account
  54.             while ($def instanceof ChildDefinition) {
  55.                 $def $container->findDefinition($def->getParent());
  56.                 $class $class ?: $def->getClass();
  57.                 $bindings += $def->getBindings();
  58.             }
  59.             $class $parameterBag->resolveValue($class);
  60.             if (!$r $container->getReflectionClass($class)) {
  61.                 throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.'$class$id));
  62.             }
  63.             $isContainerAware $r->implementsInterface(ContainerAwareInterface::class) || is_subclass_of($classAbstractController::class);
  64.             // get regular public methods
  65.             $methods = [];
  66.             $arguments = [];
  67.             foreach ($r->getMethods(\ReflectionMethod::IS_PUBLIC) as $r) {
  68.                 if ('setContainer' === $r->name && $isContainerAware) {
  69.                     continue;
  70.                 }
  71.                 if (!$r->isConstructor() && !$r->isDestructor() && !$r->isAbstract()) {
  72.                     $methods[strtolower($r->name)] = [$r$r->getParameters()];
  73.                 }
  74.             }
  75.             // validate and collect explicit per-actions and per-arguments service references
  76.             foreach ($tags as $attributes) {
  77.                 if (!isset($attributes['action']) && !isset($attributes['argument']) && !isset($attributes['id'])) {
  78.                     $autowire true;
  79.                     continue;
  80.                 }
  81.                 foreach (['action''argument''id'] as $k) {
  82.                     if (!isset($attributes[$k][0])) {
  83.                         throw new InvalidArgumentException(sprintf('Missing "%s" attribute on tag "controller.service_arguments" %s for service "%s".'$kjson_encode($attributes\JSON_UNESCAPED_UNICODE), $id));
  84.                     }
  85.                 }
  86.                 if (!isset($methods[$action strtolower($attributes['action'])])) {
  87.                     throw new InvalidArgumentException(sprintf('Invalid "action" attribute on tag "controller.service_arguments" for service "%s": no public "%s()" method found on class "%s".'$id$attributes['action'], $class));
  88.                 }
  89.                 [$r$parameters] = $methods[$action];
  90.                 $found false;
  91.                 foreach ($parameters as $p) {
  92.                     if ($attributes['argument'] === $p->name) {
  93.                         if (!isset($arguments[$r->name][$p->name])) {
  94.                             $arguments[$r->name][$p->name] = $attributes['id'];
  95.                         }
  96.                         $found true;
  97.                         break;
  98.                     }
  99.                 }
  100.                 if (!$found) {
  101.                     throw new InvalidArgumentException(sprintf('Invalid "controller.service_arguments" tag for service "%s": method "%s()" has no "%s" argument on class "%s".'$id$r->name$attributes['argument'], $class));
  102.                 }
  103.             }
  104.             foreach ($methods as [$r$parameters]) {
  105.                 /** @var \ReflectionMethod $r */
  106.                 // create a per-method map of argument-names to service/type-references
  107.                 $args = [];
  108.                 foreach ($parameters as $p) {
  109.                     /** @var \ReflectionParameter $p */
  110.                     $type ltrim($target = (string) ProxyHelper::getTypeHint($r$p), '\\');
  111.                     $invalidBehavior ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  112.                     $autowireAttributes $autowire $emptyAutowireAttributes : [];
  113.                     if (isset($arguments[$r->name][$p->name])) {
  114.                         $target $arguments[$r->name][$p->name];
  115.                         if ('?' !== $target[0]) {
  116.                             $invalidBehavior ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
  117.                         } elseif ('' === $target = (string) substr($target1)) {
  118.                             throw new InvalidArgumentException(sprintf('A "controller.service_arguments" tag must have non-empty "id" attributes for service "%s".'$id));
  119.                         } elseif ($p->allowsNull() && !$p->isOptional()) {
  120.                             $invalidBehavior ContainerInterface::NULL_ON_INVALID_REFERENCE;
  121.                         }
  122.                     } elseif (isset($bindings[$bindingName $type.' $'.$name Target::parseName($p)]) || isset($bindings[$bindingName '$'.$name]) || isset($bindings[$bindingName $type])) {
  123.                         $binding $bindings[$bindingName];
  124.                         [$bindingValue$bindingId, , $bindingType$bindingFile] = $binding->getValues();
  125.                         $binding->setValues([$bindingValue$bindingIdtrue$bindingType$bindingFile]);
  126.                         $args[$p->name] = $bindingValue;
  127.                         continue;
  128.                     } elseif (!$autowire || (!($autowireAttributes ??= $p->getAttributes(Autowire::class)) && (!$type || '\\' !== $target[0]))) {
  129.                         continue;
  130.                     } elseif (is_subclass_of($type\UnitEnum::class)) {
  131.                         // do not attempt to register enum typed arguments if not already present in bindings
  132.                         continue;
  133.                     } elseif (!$p->allowsNull()) {
  134.                         $invalidBehavior ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
  135.                     }
  136.                     if (Request::class === $type || SessionInterface::class === $type) {
  137.                         continue;
  138.                     }
  139.                     if ($autowireAttributes) {
  140.                         $value $autowireAttributes[0]->newInstance()->value;
  141.                         if ($value instanceof Reference) {
  142.                             $args[$p->name] = $type ? new TypedReference($value$type$invalidBehavior$p->name) : new Reference($value$invalidBehavior);
  143.                         } else {
  144.                             $args[$p->name] = new Reference('.value.'.$container->hash($value));
  145.                             $container->register((string) $args[$p->name], 'mixed')
  146.                                 ->setFactory('current')
  147.                                 ->addArgument([$value]);
  148.                         }
  149.                         continue;
  150.                     }
  151.                     if ($type && !$p->isOptional() && !$p->allowsNull() && !class_exists($type) && !interface_exists($typefalse)) {
  152.                         $message sprintf('Cannot determine controller argument for "%s::%s()": the $%s argument is type-hinted with the non-existent class or interface: "%s".'$class$r->name$p->name$type);
  153.                         // see if the type-hint lives in the same namespace as the controller
  154.                         if (=== strncmp($type$classstrrpos($class'\\'))) {
  155.                             $message .= ' Did you forget to add a use statement?';
  156.                         }
  157.                         $container->register($erroredId '.errored.'.$container->hash($message), $type)
  158.                             ->addError($message);
  159.                         $args[$p->name] = new Reference($erroredIdContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE);
  160.                     } else {
  161.                         $target ltrim($target'\\');
  162.                         $args[$p->name] = $type ? new TypedReference($target$type$invalidBehaviorTarget::parseName($p)) : new Reference($target$invalidBehavior);
  163.                     }
  164.                 }
  165.                 // register the maps as a per-method service-locators
  166.                 if ($args) {
  167.                     $controllers[$id.'::'.$r->name] = ServiceLocatorTagPass::register($container$args);
  168.                     foreach ($publicAliases[$id] ?? [] as $alias) {
  169.                         $controllers[$alias.'::'.$r->name] = clone $controllers[$id.'::'.$r->name];
  170.                     }
  171.                 }
  172.             }
  173.         }
  174.         $controllerLocatorRef ServiceLocatorTagPass::register($container$controllers);
  175.         if ($container->hasDefinition('argument_resolver.service')) {
  176.             $container->getDefinition('argument_resolver.service')
  177.                 ->replaceArgument(0$controllerLocatorRef);
  178.         }
  179.         if ($container->hasDefinition('argument_resolver.not_tagged_controller')) {
  180.             $container->getDefinition('argument_resolver.not_tagged_controller')
  181.                 ->replaceArgument(0$controllerLocatorRef);
  182.         }
  183.         $container->setAlias('argument_resolver.controller_locator', (string) $controllerLocatorRef);
  184.     }
  185. }