RegisterControllerArgumentLocatorsPass.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. $publicAliases = [];
  49. foreach ($container->getAliases() as $id => $alias) {
  50. if ($alias->isPublic() && !$alias->isPrivate()) {
  51. $publicAliases[(string) $alias][] = $id;
  52. }
  53. }
  54. foreach ($container->findTaggedServiceIds($this->controllerTag, true) as $id => $tags) {
  55. $def = $container->getDefinition($id);
  56. $def->setPublic(true);
  57. $class = $def->getClass();
  58. $autowire = $def->isAutowired();
  59. $bindings = $def->getBindings();
  60. // resolve service class, taking parent definitions into account
  61. while ($def instanceof ChildDefinition) {
  62. $def = $container->findDefinition($def->getParent());
  63. $class = $class ?: $def->getClass();
  64. $bindings += $def->getBindings();
  65. }
  66. $class = $parameterBag->resolveValue($class);
  67. if (!$r = $container->getReflectionClass($class)) {
  68. throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
  69. }
  70. $isContainerAware = $r->implementsInterface(ContainerAwareInterface::class) || is_subclass_of($class, AbstractController::class);
  71. // get regular public methods
  72. $methods = [];
  73. $arguments = [];
  74. foreach ($r->getMethods(\ReflectionMethod::IS_PUBLIC) as $r) {
  75. if ('setContainer' === $r->name && $isContainerAware) {
  76. continue;
  77. }
  78. if (!$r->isConstructor() && !$r->isDestructor() && !$r->isAbstract()) {
  79. $methods[strtolower($r->name)] = [$r, $r->getParameters()];
  80. }
  81. }
  82. // validate and collect explicit per-actions and per-arguments service references
  83. foreach ($tags as $attributes) {
  84. if (!isset($attributes['action']) && !isset($attributes['argument']) && !isset($attributes['id'])) {
  85. $autowire = true;
  86. continue;
  87. }
  88. foreach (['action', 'argument', 'id'] as $k) {
  89. if (!isset($attributes[$k][0])) {
  90. throw new InvalidArgumentException(sprintf('Missing "%s" attribute on tag "%s" %s for service "%s".', $k, $this->controllerTag, json_encode($attributes, \JSON_UNESCAPED_UNICODE), $id));
  91. }
  92. }
  93. if (!isset($methods[$action = strtolower($attributes['action'])])) {
  94. 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));
  95. }
  96. [$r, $parameters] = $methods[$action];
  97. $found = false;
  98. foreach ($parameters as $p) {
  99. if ($attributes['argument'] === $p->name) {
  100. if (!isset($arguments[$r->name][$p->name])) {
  101. $arguments[$r->name][$p->name] = $attributes['id'];
  102. }
  103. $found = true;
  104. break;
  105. }
  106. }
  107. if (!$found) {
  108. 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));
  109. }
  110. }
  111. foreach ($methods as [$r, $parameters]) {
  112. /** @var \ReflectionMethod $r */
  113. // create a per-method map of argument-names to service/type-references
  114. $args = [];
  115. foreach ($parameters as $p) {
  116. /** @var \ReflectionParameter $p */
  117. $type = ltrim($target = ProxyHelper::getTypeHint($r, $p), '\\');
  118. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  119. if (isset($arguments[$r->name][$p->name])) {
  120. $target = $arguments[$r->name][$p->name];
  121. if ('?' !== $target[0]) {
  122. $invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
  123. } elseif ('' === $target = (string) substr($target, 1)) {
  124. throw new InvalidArgumentException(sprintf('A "%s" tag must have non-empty "id" attributes for service "%s".', $this->controllerTag, $id));
  125. } elseif ($p->allowsNull() && !$p->isOptional()) {
  126. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
  127. }
  128. } elseif (isset($bindings[$bindingName = $type.' $'.$p->name]) || isset($bindings[$bindingName = '$'.$p->name]) || isset($bindings[$bindingName = $type])) {
  129. $binding = $bindings[$bindingName];
  130. [$bindingValue, $bindingId, , $bindingType, $bindingFile] = $binding->getValues();
  131. $binding->setValues([$bindingValue, $bindingId, true, $bindingType, $bindingFile]);
  132. if (!$bindingValue instanceof Reference) {
  133. $args[$p->name] = new Reference('.value.'.$container->hash($bindingValue));
  134. $container->register((string) $args[$p->name], 'mixed')
  135. ->setFactory('current')
  136. ->addArgument([$bindingValue]);
  137. } else {
  138. $args[$p->name] = $bindingValue;
  139. }
  140. continue;
  141. } elseif (!$type || !$autowire || '\\' !== $target[0]) {
  142. continue;
  143. } elseif (!$p->allowsNull()) {
  144. $invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
  145. }
  146. if (Request::class === $type) {
  147. continue;
  148. }
  149. if ($type && !$p->isOptional() && !$p->allowsNull() && !class_exists($type) && !interface_exists($type, false)) {
  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 (0 === strncmp($type, $class, strrpos($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($erroredId, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE);
  158. } else {
  159. $target = ltrim($target, '\\');
  160. $args[$p->name] = $type ? new TypedReference($target, $type, $invalidBehavior, $p->name) : 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($this->resolverServiceId)) {
  174. $container->getDefinition($this->resolverServiceId)
  175. ->replaceArgument(0, $controllerLocatorRef);
  176. }
  177. if ($container->hasDefinition($this->notTaggedControllerResolverServiceId)) {
  178. $container->getDefinition($this->notTaggedControllerResolverServiceId)
  179. ->replaceArgument(0, $controllerLocatorRef);
  180. }
  181. $container->setAlias($this->controllerLocator, (string) $controllerLocatorRef);
  182. }
  183. }