You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

220 lines
11 KiB

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