Açıklama Yok

RegisterControllerArgumentLocatorsPass.php 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. foreach ($container->findTaggedServiceIds($this->controllerTag, true) as $id => $tags) {
  49. $def = $container->getDefinition($id);
  50. $def->setPublic(true);
  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. $isContainerAware = $r->implementsInterface(ContainerAwareInterface::class) || is_subclass_of($class, AbstractController::class);
  65. // get regular public methods
  66. $methods = [];
  67. $arguments = [];
  68. foreach ($r->getMethods(\ReflectionMethod::IS_PUBLIC) as $r) {
  69. if ('setContainer' === $r->name && $isContainerAware) {
  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 "%s" %s for service "%s".', $k, $this->controllerTag, 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 "%s" for service "%s": no public "%s()" method found on class "%s".', $this->controllerTag, $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 "%s" tag for service "%s": method "%s()" has no "%s" argument on class "%s".', $this->controllerTag, $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. foreach ($parameters as $p) {
  110. /** @var \ReflectionParameter $p */
  111. $type = ltrim($target = (string) ProxyHelper::getTypeHint($r, $p), '\\');
  112. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  113. if (isset($arguments[$r->name][$p->name])) {
  114. $target = $arguments[$r->name][$p->name];
  115. if ('?' !== $target[0]) {
  116. $invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
  117. } elseif ('' === $target = (string) substr($target, 1)) {
  118. throw new InvalidArgumentException(sprintf('A "%s" tag must have non-empty "id" attributes for service "%s".', $this->controllerTag, $id));
  119. } elseif ($p->allowsNull() && !$p->isOptional()) {
  120. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
  121. }
  122. } elseif (isset($bindings[$bindingName = $type.' $'.$p->name]) || isset($bindings[$bindingName = '$'.$p->name]) || isset($bindings[$bindingName = $type])) {
  123. $binding = $bindings[$bindingName];
  124. [$bindingValue, $bindingId, , $bindingType, $bindingFile] = $binding->getValues();
  125. $binding->setValues([$bindingValue, $bindingId, true, $bindingType, $bindingFile]);
  126. if (!$bindingValue instanceof Reference) {
  127. $args[$p->name] = new Reference('.value.'.$container->hash($bindingValue));
  128. $container->register((string) $args[$p->name], 'mixed')
  129. ->setFactory('current')
  130. ->addArgument([$bindingValue]);
  131. } else {
  132. $args[$p->name] = $bindingValue;
  133. }
  134. continue;
  135. } elseif (!$type || !$autowire || '\\' !== $target[0]) {
  136. continue;
  137. } elseif (is_subclass_of($type, \UnitEnum::class)) {
  138. // do not attempt to register enum typed arguments if not already present in bindings
  139. continue;
  140. } elseif (!$p->allowsNull()) {
  141. $invalidBehavior = ContainerInterface::RUNTIME_EXCEPTION_ON_INVALID_REFERENCE;
  142. }
  143. if (Request::class === $type) {
  144. continue;
  145. }
  146. if ($type && !$p->isOptional() && !$p->allowsNull() && !class_exists($type) && !interface_exists($type, false)) {
  147. $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);
  148. // see if the type-hint lives in the same namespace as the controller
  149. if (0 === strncmp($type, $class, strrpos($class, '\\'))) {
  150. $message .= ' Did you forget to add a use statement?';
  151. }
  152. throw new InvalidArgumentException($message);
  153. }
  154. $target = ltrim($target, '\\');
  155. $args[$p->name] = $type ? new TypedReference($target, $type, $invalidBehavior, $p->name) : new Reference($target, $invalidBehavior);
  156. }
  157. // register the maps as a per-method service-locators
  158. if ($args) {
  159. $controllers[$id.'::'.$r->name] = ServiceLocatorTagPass::register($container, $args);
  160. }
  161. }
  162. }
  163. $controllerLocatorRef = ServiceLocatorTagPass::register($container, $controllers);
  164. if ($container->hasDefinition($this->resolverServiceId)) {
  165. $container->getDefinition($this->resolverServiceId)
  166. ->replaceArgument(0, $controllerLocatorRef);
  167. }
  168. if ($container->hasDefinition($this->notTaggedControllerResolverServiceId)) {
  169. $container->getDefinition($this->notTaggedControllerResolverServiceId)
  170. ->replaceArgument(0, $controllerLocatorRef);
  171. }
  172. $container->setAlias($this->controllerLocator, (string) $controllerLocatorRef);
  173. }
  174. }