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

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\ChildDefinition;
  13. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  14. use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
  15. use Symfony\Component\DependencyInjection\ContainerAwareInterface;
  16. use Symfony\Component\DependencyInjection\ContainerBuilder;
  17. use Symfony\Component\DependencyInjection\ContainerInterface;
  18. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  19. use Symfony\Component\DependencyInjection\LazyProxy\ProxyHelper;
  20. use Symfony\Component\DependencyInjection\Reference;
  21. use Symfony\Component\DependencyInjection\TypedReference;
  22. use Symfony\Component\HttpFoundation\Request;
  23. /**
  24.  * Creates the service-locators required by ServiceValueResolver.
  25.  *
  26.  * @author Nicolas Grekas <p@tchwork.com>
  27.  */
  28. class RegisterControllerArgumentLocatorsPass implements CompilerPassInterface
  29. {
  30.     private $resolverServiceId;
  31.     private $controllerTag;
  32.     private $controllerLocator;
  33.     private $notTaggedControllerResolverServiceId;
  34.     public function __construct(string $resolverServiceId 'argument_resolver.service'string $controllerTag 'controller.service_arguments'string $controllerLocator 'argument_resolver.controller_locator'string $notTaggedControllerResolverServiceId 'argument_resolver.not_tagged_controller')
  35.     {
  36.         $this->resolverServiceId $resolverServiceId;
  37.         $this->controllerTag $controllerTag;
  38.         $this->controllerLocator $controllerLocator;
  39.         $this->notTaggedControllerResolverServiceId $notTaggedControllerResolverServiceId;
  40.     }
  41.     public function process(ContainerBuilder $container)
  42.     {
  43.         if (false === $container->hasDefinition($this->resolverServiceId) && false === $container->hasDefinition($this->notTaggedControllerResolverServiceId)) {
  44.             return;
  45.         }
  46.         $parameterBag $container->getParameterBag();
  47.         $controllers = [];
  48.         foreach ($container->findTaggedServiceIds($this->controllerTagtrue) 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($classAbstractController::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 "%s" %s for service "%s".'$k$this->controllerTagjson_encode($attributesJSON_UNESCAPED_UNICODE), $id));
  85.                     }
  86.                 }
  87.                 if (!isset($methods[$action strtolower($attributes['action'])])) {
  88.                     throw new InvalidArgumentException(sprintf('Invalid "action" attribute on tag "%s" for service "%s": no public "%s()" method found on class "%s".'$this->controllerTag$id$attributes['action'], $class));
  89.                 }
  90.                 list($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 "%s" tag for service "%s": method "%s()" has no "%s" argument on class "%s".'$this->controllerTag$id$r->name$attributes['argument'], $class));
  103.                 }
  104.             }
  105.             foreach ($methods as list($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 ProxyHelper::getTypeHint($r$p), '\\');
  112.                     $invalidBehavior ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  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 "%s" tag must have non-empty "id" attributes for service "%s".'$this->controllerTag$id));
  119.                         } elseif ($p->allowsNull() && !$p->isOptional()) {
  120.                             $invalidBehavior ContainerInterface::NULL_ON_INVALID_REFERENCE;
  121.                         }
  122.                     } elseif (isset($bindings[$bindingName $type.' $'.$p->name]) || isset($bindings[$bindingName '$'.$p->name]) || isset($bindings[$bindingName $type])) {
  123.                         $binding $bindings[$bindingName];
  124.                         list($bindingValue$bindingId, , $bindingType$bindingFile) = $binding->getValues();
  125.                         $binding->setValues([$bindingValue$bindingIdtrue$bindingType$bindingFile]);
  126.                         if (!$bindingValue instanceof Reference) {
  127.                             $args[$p->name] = new Reference('.value.'.$container->hash($bindingValue));
  128.                             $container->register((string) $args[$p->name], 'mixed')
  129.                                 ->setFactory('current')
  130.                                 ->addArgument([$bindingValue]);
  131.                         } else {
  132.                             $args[$p->name] = $bindingValue;
  133.                         }
  134.                         continue;
  135.                     } elseif (!$type || !$autowire || '\\' !== $target[0]) {
  136.                         continue;
  137.                     } elseif (!$p->allowsNull()) {
  138.                         $invalidBehavior ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
  139.                     }
  140.                     if (Request::class === $type) {
  141.                         continue;
  142.                     }
  143.                     if ($type && !$p->isOptional() && !$p->allowsNull() && !class_exists($type) && !interface_exists($typefalse)) {
  144.                         $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);
  145.                         // see if the type-hint lives in the same namespace as the controller
  146.                         if (=== strncmp($type$classstrrpos($class'\\'))) {
  147.                             $message .= ' Did you forget to add a use statement?';
  148.                         }
  149.                         throw new InvalidArgumentException($message);
  150.                     }
  151.                     $target ltrim($target'\\');
  152.                     $args[$p->name] = $type ? new TypedReference($target$type$invalidBehavior$p->name) : new Reference($target$invalidBehavior);
  153.                 }
  154.                 // register the maps as a per-method service-locators
  155.                 if ($args) {
  156.                     $controllers[$id.'::'.$r->name] = ServiceLocatorTagPass::register($container$args);
  157.                 }
  158.             }
  159.         }
  160.         $controllerLocatorRef ServiceLocatorTagPass::register($container$controllers);
  161.         if ($container->hasDefinition($this->resolverServiceId)) {
  162.             $container->getDefinition($this->resolverServiceId)
  163.                 ->replaceArgument(0$controllerLocatorRef);
  164.         }
  165.         if ($container->hasDefinition($this->notTaggedControllerResolverServiceId)) {
  166.             $container->getDefinition($this->notTaggedControllerResolverServiceId)
  167.                 ->replaceArgument(0$controllerLocatorRef);
  168.         }
  169.         $container->setAlias($this->controllerLocator, (string) $controllerLocatorRef);
  170.     }
  171. }