RegisterControllerArgumentLocatorsPass.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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\Component\DependencyInjection\Attribute\Autowire;
  12. use Symfony\Component\DependencyInjection\Attribute\AutowireCallable;
  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\ContainerBuilder;
  18. use Symfony\Component\DependencyInjection\ContainerInterface;
  19. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  20. use Symfony\Component\DependencyInjection\Reference;
  21. use Symfony\Component\DependencyInjection\TypedReference;
  22. use Symfony\Component\HttpFoundation\Request;
  23. use Symfony\Component\HttpFoundation\Response;
  24. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  25. use Symfony\Component\VarExporter\ProxyHelper;
  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. public function process(ContainerBuilder $container): void
  34. {
  35. if (!$container->hasDefinition('argument_resolver.service') && !$container->hasDefinition('argument_resolver.not_tagged_controller')) {
  36. return;
  37. }
  38. $parameterBag = $container->getParameterBag();
  39. $controllers = [];
  40. $controllerClasses = [];
  41. $publicAliases = [];
  42. foreach ($container->getAliases() as $id => $alias) {
  43. if ($alias->isPublic()) {
  44. $publicAliases[(string) $alias][] = $id;
  45. }
  46. }
  47. foreach ($container->findTaggedServiceIds('controller.service_arguments', true) as $id => $tags) {
  48. $def = $container->getDefinition($id);
  49. $def->setPublic(true);
  50. $def->setLazy(false);
  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. $controllerClasses[] = $class;
  65. // get regular public methods
  66. $methods = [];
  67. $arguments = [];
  68. foreach ($r->getMethods(\ReflectionMethod::IS_PUBLIC) as $r) {
  69. if ('setContainer' === $r->name) {
  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. $erroredIds = 0;
  110. foreach ($parameters as $p) {
  111. /** @var \ReflectionParameter $p */
  112. $type = preg_replace('/(^|[(|&])\\\\/', '\1', $target = ltrim(ProxyHelper::exportType($p) ?? '', '?'));
  113. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  114. $autowireAttributes = null;
  115. $parsedName = $p->name;
  116. $k = null;
  117. if (isset($arguments[$r->name][$p->name])) {
  118. $target = $arguments[$r->name][$p->name];
  119. if ('?' !== $target[0]) {
  120. $invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
  121. } elseif ('' === $target = substr($target, 1)) {
  122. throw new InvalidArgumentException(\sprintf('A "controller.service_arguments" tag must have non-empty "id" attributes for service "%s".', $id));
  123. } elseif ($p->allowsNull() && !$p->isOptional()) {
  124. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
  125. }
  126. } elseif (isset($bindings[$bindingName = $type.' $'.$name = Target::parseName($p, $k, $parsedName)])
  127. || isset($bindings[$bindingName = $type.' $'.$parsedName])
  128. || isset($bindings[$bindingName = '$'.$name])
  129. || isset($bindings[$bindingName = $type])
  130. ) {
  131. $binding = $bindings[$bindingName];
  132. [$bindingValue, $bindingId, , $bindingType, $bindingFile] = $binding->getValues();
  133. $binding->setValues([$bindingValue, $bindingId, true, $bindingType, $bindingFile]);
  134. $args[$p->name] = $bindingValue;
  135. continue;
  136. } elseif (!$autowire || (!($autowireAttributes = $p->getAttributes(Autowire::class, \ReflectionAttribute::IS_INSTANCEOF)) && (!$type || '\\' !== $target[0]))) {
  137. continue;
  138. } elseif (!$autowireAttributes && is_subclass_of($type, \UnitEnum::class)) {
  139. // do not attempt to register enum typed arguments if not already present in bindings
  140. continue;
  141. } elseif (!$p->allowsNull()) {
  142. $invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
  143. }
  144. if (Request::class === $type || SessionInterface::class === $type || Response::class === $type) {
  145. continue;
  146. }
  147. if ($autowireAttributes) {
  148. $attribute = $autowireAttributes[0]->newInstance();
  149. $value = $parameterBag->resolveValue($attribute->value);
  150. if ($attribute instanceof AutowireCallable) {
  151. $args[$p->name] = $attribute->buildDefinition($value, $type, $p);
  152. } elseif ($value instanceof Reference) {
  153. $args[$p->name] = $type ? new TypedReference($value, $type, $invalidBehavior, $p->name) : new Reference($value, $invalidBehavior);
  154. } else {
  155. $args[$p->name] = new Reference('.value.'.$container->hash($value));
  156. $container->register((string) $args[$p->name], 'mixed')
  157. ->setFactory('current')
  158. ->addArgument([$value]);
  159. }
  160. continue;
  161. }
  162. if ($type && !$p->isOptional() && !$p->allowsNull() && !class_exists($type) && !interface_exists($type, false)) {
  163. $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);
  164. // see if the type-hint lives in the same namespace as the controller
  165. if (0 === strncmp($type, $class, strrpos($class, '\\'))) {
  166. $message .= ' Did you forget to add a use statement?';
  167. }
  168. $container->register($erroredId = '.errored.'.$container->hash($message), $type)
  169. ->addError($message);
  170. $args[$p->name] = new Reference($erroredId, ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE);
  171. ++$erroredIds;
  172. } else {
  173. $target = preg_replace('/(^|[(|&])\\\\/', '\1', $target);
  174. $args[$p->name] = $type ? new TypedReference($target, $type, $invalidBehavior, Target::parseName($p)) : new Reference($target, $invalidBehavior);
  175. }
  176. }
  177. // register the maps as a per-method service-locators
  178. if ($args) {
  179. $controllers[$id.'::'.$r->name] = ServiceLocatorTagPass::register($container, $args, \count($args) !== $erroredIds ? $id.'::'.$r->name.'()' : null);
  180. foreach ($publicAliases[$id] ?? [] as $alias) {
  181. $controllers[$alias.'::'.$r->name] = clone $controllers[$id.'::'.$r->name];
  182. }
  183. }
  184. }
  185. }
  186. $controllerLocatorRef = ServiceLocatorTagPass::register($container, $controllers);
  187. if ($container->hasDefinition('argument_resolver.service')) {
  188. $container->getDefinition('argument_resolver.service')
  189. ->replaceArgument(0, $controllerLocatorRef);
  190. }
  191. if ($container->hasDefinition('argument_resolver.not_tagged_controller')) {
  192. $container->getDefinition('argument_resolver.not_tagged_controller')
  193. ->replaceArgument(0, $controllerLocatorRef);
  194. }
  195. $container->setAlias('argument_resolver.controller_locator', (string) $controllerLocatorRef);
  196. if ($container->hasDefinition('controller_resolver')) {
  197. $container->getDefinition('controller_resolver')
  198. ->addMethodCall('allowControllers', [array_unique($controllerClasses)]);
  199. }
  200. }
  201. }