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

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\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\ContainerAwareInterface;
  17. use Symfony\Component\DependencyInjection\ContainerBuilder;
  18. use Symfony\Component\DependencyInjection\ContainerInterface;
  19. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  20. use Symfony\Component\DependencyInjection\LazyProxy\ProxyHelper;
  21. use Symfony\Component\DependencyInjection\Reference;
  22. use Symfony\Component\DependencyInjection\TypedReference;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use Symfony\Component\HttpFoundation\Response;
  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.         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.             $isContainerAware $r->implementsInterface(ContainerAwareInterface::class) || is_subclass_of($classAbstractController::class);
  63.             // get regular public methods
  64.             $methods = [];
  65.             $arguments = [];
  66.             foreach ($r->getMethods(\ReflectionMethod::IS_PUBLIC) as $r) {
  67.                 if ('setContainer' === $r->name && $isContainerAware) {
  68.                     continue;
  69.                 }
  70.                 if (!$r->isConstructor() && !$r->isDestructor() && !$r->isAbstract()) {
  71.                     $methods[strtolower($r->name)] = [$r$r->getParameters()];
  72.                 }
  73.             }
  74.             // validate and collect explicit per-actions and per-arguments service references
  75.             foreach ($tags as $attributes) {
  76.                 if (!isset($attributes['action']) && !isset($attributes['argument']) && !isset($attributes['id'])) {
  77.                     $autowire true;
  78.                     continue;
  79.                 }
  80.                 foreach (['action''argument''id'] as $k) {
  81.                     if (!isset($attributes[$k][0])) {
  82.                         throw new InvalidArgumentException(sprintf('Missing "%s" attribute on tag "controller.service_arguments" %s for service "%s".'$kjson_encode($attributes\JSON_UNESCAPED_UNICODE), $id));
  83.                     }
  84.                 }
  85.                 if (!isset($methods[$action strtolower($attributes['action'])])) {
  86.                     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));
  87.                 }
  88.                 [$r$parameters] = $methods[$action];
  89.                 $found false;
  90.                 foreach ($parameters as $p) {
  91.                     if ($attributes['argument'] === $p->name) {
  92.                         if (!isset($arguments[$r->name][$p->name])) {
  93.                             $arguments[$r->name][$p->name] = $attributes['id'];
  94.                         }
  95.                         $found true;
  96.                         break;
  97.                     }
  98.                 }
  99.                 if (!$found) {
  100.                     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));
  101.                 }
  102.             }
  103.             foreach ($methods as [$r$parameters]) {
  104.                 /** @var \ReflectionMethod $r */
  105.                 // create a per-method map of argument-names to service/type-references
  106.                 $args = [];
  107.                 foreach ($parameters as $p) {
  108.                     /** @var \ReflectionParameter $p */
  109.                     $type ltrim($target = (string) ProxyHelper::getTypeHint($r$p), '\\');
  110.                     $invalidBehavior ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  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.                         if (!$bindingValue instanceof Reference) {
  125.                             $args[$p->name] = new Reference('.value.'.$container->hash($bindingValue));
  126.                             $container->register((string) $args[$p->name], 'mixed')
  127.                                 ->setFactory('current')
  128.                                 ->addArgument([$bindingValue]);
  129.                         } else {
  130.                             $args[$p->name] = $bindingValue;
  131.                         }
  132.                         continue;
  133.                     } elseif (!$type || !$autowire || '\\' !== $target[0]) {
  134.                         continue;
  135.                     } elseif (is_subclass_of($type\UnitEnum::class)) {
  136.                         // do not attempt to register enum typed arguments if not already present in bindings
  137.                         continue;
  138.                     } elseif (!$p->allowsNull()) {
  139.                         $invalidBehavior ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
  140.                     }
  141.                     if (Request::class === $type || SessionInterface::class === $type || Response::class === $type) {
  142.                         continue;
  143.                     }
  144.                     if ($type && !$p->isOptional() && !$p->allowsNull() && !class_exists($type) && !interface_exists($typefalse)) {
  145.                         $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);
  146.                         // see if the type-hint lives in the same namespace as the controller
  147.                         if (=== strncmp($type$classstrrpos($class'\\'))) {
  148.                             $message .= ' Did you forget to add a use statement?';
  149.                         }
  150.                         $container->register($erroredId '.errored.'.$container->hash($message), $type)
  151.                             ->addError($message);
  152.                         $args[$p->name] = new Reference($erroredIdContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE);
  153.                     } else {
  154.                         $target ltrim($target'\\');
  155.                         $args[$p->name] = $type ? new TypedReference($target$type$invalidBehaviorTarget::parseName($p)) : new Reference($target$invalidBehavior);
  156.                     }
  157.                 }
  158.                 // register the maps as a per-method service-locators
  159.                 if ($args) {
  160.                     $controllers[$id.'::'.$r->name] = ServiceLocatorTagPass::register($container$args);
  161.                     foreach ($publicAliases[$id] ?? [] as $alias) {
  162.                         $controllers[$alias.'::'.$r->name] = clone $controllers[$id.'::'.$r->name];
  163.                     }
  164.                 }
  165.             }
  166.         }
  167.         $controllerLocatorRef ServiceLocatorTagPass::register($container$controllers);
  168.         if ($container->hasDefinition('argument_resolver.service')) {
  169.             $container->getDefinition('argument_resolver.service')
  170.                 ->replaceArgument(0$controllerLocatorRef);
  171.         }
  172.         if ($container->hasDefinition('argument_resolver.not_tagged_controller')) {
  173.             $container->getDefinition('argument_resolver.not_tagged_controller')
  174.                 ->replaceArgument(0$controllerLocatorRef);
  175.         }
  176.         $container->setAlias('argument_resolver.controller_locator', (string) $controllerLocatorRef);
  177.     }
  178. }