RegisterControllerArgumentLocatorsPass.php 12 KB

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