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

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