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

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