RegisterControllerArgumentLocatorsPass.php 11 KB

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