RegisterControllerArgumentLocatorsPass.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. public function __construct(string $resolverServiceId = 'argument_resolver.service', string $controllerTag = 'controller.service_arguments', string $controllerLocator = 'argument_resolver.controller_locator')
  34. {
  35. $this->resolverServiceId = $resolverServiceId;
  36. $this->controllerTag = $controllerTag;
  37. $this->controllerLocator = $controllerLocator;
  38. }
  39. public function process(ContainerBuilder $container)
  40. {
  41. if (false === $container->hasDefinition($this->resolverServiceId)) {
  42. return;
  43. }
  44. $parameterBag = $container->getParameterBag();
  45. $controllers = [];
  46. foreach ($container->findTaggedServiceIds($this->controllerTag, 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($class, AbstractController::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 "%s" %s for service "%s".', $k, $this->controllerTag, json_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 "%s" for service "%s": no public "%s()" method found on class "%s".', $this->controllerTag, $id, $attributes['action'], $class));
  87. }
  88. list($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 "%s" tag for service "%s": method "%s()" has no "%s" argument on class "%s".', $this->controllerTag, $id, $r->name, $attributes['argument'], $class));
  101. }
  102. }
  103. foreach ($methods as list($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 = 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($target, 1)) {
  116. throw new InvalidArgumentException(sprintf('A "%s" tag must have non-empty "id" attributes for service "%s".', $this->controllerTag, $id));
  117. } elseif ($p->allowsNull() && !$p->isOptional()) {
  118. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
  119. }
  120. } elseif (isset($bindings[$bindingName = $type.' $'.$p->name]) || isset($bindings[$bindingName = '$'.$p->name]) || isset($bindings[$bindingName = $type])) {
  121. $binding = $bindings[$bindingName];
  122. list($bindingValue, $bindingId) = $binding->getValues();
  123. $binding->setValues([$bindingValue, $bindingId, true]);
  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 (!$p->allowsNull()) {
  136. $invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
  137. }
  138. if (Request::class === $type) {
  139. continue;
  140. }
  141. if ($type && !$p->isOptional() && !$p->allowsNull() && !class_exists($type) && !interface_exists($type, false)) {
  142. $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);
  143. // see if the type-hint lives in the same namespace as the controller
  144. if (0 === strncmp($type, $class, strrpos($class, '\\'))) {
  145. $message .= ' Did you forget to add a use statement?';
  146. }
  147. throw new InvalidArgumentException($message);
  148. }
  149. $target = ltrim($target, '\\');
  150. $args[$p->name] = $type ? new TypedReference($target, $type, $invalidBehavior, $p->name) : new Reference($target, $invalidBehavior);
  151. }
  152. // register the maps as a per-method service-locators
  153. if ($args) {
  154. $controllers[$id.'::'.$r->name] = ServiceLocatorTagPass::register($container, $args);
  155. }
  156. }
  157. }
  158. $container->getDefinition($this->resolverServiceId)
  159. ->replaceArgument(0, $controllerLocatorRef = ServiceLocatorTagPass::register($container, $controllers));
  160. $container->setAlias($this->controllerLocator, (string) $controllerLocatorRef);
  161. }
  162. }