RegisterControllerArgumentLocatorsPass.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. public function __construct($resolverServiceId = 'argument_resolver.service', $controllerTag = 'controller.service_arguments')
  33. {
  34. $this->resolverServiceId = $resolverServiceId;
  35. $this->controllerTag = $controllerTag;
  36. }
  37. public function process(ContainerBuilder $container)
  38. {
  39. if (false === $container->hasDefinition($this->resolverServiceId)) {
  40. return;
  41. }
  42. $parameterBag = $container->getParameterBag();
  43. $controllers = [];
  44. foreach ($container->findTaggedServiceIds($this->controllerTag, true) as $id => $tags) {
  45. $def = $container->getDefinition($id);
  46. $def->setPublic(true);
  47. $class = $def->getClass();
  48. $autowire = $def->isAutowired();
  49. $bindings = $def->getBindings();
  50. // resolve service class, taking parent definitions into account
  51. while ($def instanceof ChildDefinition) {
  52. $def = $container->findDefinition($def->getParent());
  53. $class = $class ?: $def->getClass();
  54. $bindings += $def->getBindings();
  55. }
  56. $class = $parameterBag->resolveValue($class);
  57. if (!$r = $container->getReflectionClass($class)) {
  58. throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
  59. }
  60. $isContainerAware = $r->implementsInterface(ContainerAwareInterface::class) || is_subclass_of($class, AbstractController::class);
  61. // get regular public methods
  62. $methods = [];
  63. $arguments = [];
  64. foreach ($r->getMethods(\ReflectionMethod::IS_PUBLIC) as $r) {
  65. if ('setContainer' === $r->name && $isContainerAware) {
  66. continue;
  67. }
  68. if (!$r->isConstructor() && !$r->isDestructor() && !$r->isAbstract()) {
  69. $methods[strtolower($r->name)] = [$r, $r->getParameters()];
  70. }
  71. }
  72. // validate and collect explicit per-actions and per-arguments service references
  73. foreach ($tags as $attributes) {
  74. if (!isset($attributes['action']) && !isset($attributes['argument']) && !isset($attributes['id'])) {
  75. $autowire = true;
  76. continue;
  77. }
  78. foreach (['action', 'argument', 'id'] as $k) {
  79. if (!isset($attributes[$k][0])) {
  80. throw new InvalidArgumentException(sprintf('Missing "%s" attribute on tag "%s" %s for service "%s".', $k, $this->controllerTag, json_encode($attributes, JSON_UNESCAPED_UNICODE), $id));
  81. }
  82. }
  83. if (!isset($methods[$action = strtolower($attributes['action'])])) {
  84. 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));
  85. }
  86. list($r, $parameters) = $methods[$action];
  87. $found = false;
  88. foreach ($parameters as $p) {
  89. if ($attributes['argument'] === $p->name) {
  90. if (!isset($arguments[$r->name][$p->name])) {
  91. $arguments[$r->name][$p->name] = $attributes['id'];
  92. }
  93. $found = true;
  94. break;
  95. }
  96. }
  97. if (!$found) {
  98. 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));
  99. }
  100. }
  101. foreach ($methods as list($r, $parameters)) {
  102. /** @var \ReflectionMethod $r */
  103. // create a per-method map of argument-names to service/type-references
  104. $args = [];
  105. foreach ($parameters as $p) {
  106. /** @var \ReflectionParameter $p */
  107. $type = $target = ProxyHelper::getTypeHint($r, $p, true);
  108. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  109. if (isset($arguments[$r->name][$p->name])) {
  110. $target = $arguments[$r->name][$p->name];
  111. if ('?' !== $target[0]) {
  112. $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  113. } elseif ('' === $target = (string) substr($target, 1)) {
  114. throw new InvalidArgumentException(sprintf('A "%s" tag must have non-empty "id" attributes for service "%s".', $this->controllerTag, $id));
  115. } elseif ($p->allowsNull() && !$p->isOptional()) {
  116. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
  117. }
  118. } elseif (isset($bindings[$bindingName = '$'.$p->name]) || isset($bindings[$bindingName = $type])) {
  119. $binding = $bindings[$bindingName];
  120. list($bindingValue, $bindingId) = $binding->getValues();
  121. if (!$bindingValue instanceof Reference) {
  122. continue;
  123. }
  124. $binding->setValues([$bindingValue, $bindingId, true]);
  125. $args[$p->name] = $bindingValue;
  126. continue;
  127. } elseif (!$type || !$autowire) {
  128. continue;
  129. }
  130. if (Request::class === $type) {
  131. continue;
  132. }
  133. if ($type && !$p->isOptional() && !$p->allowsNull() && !class_exists($type) && !interface_exists($type, false)) {
  134. $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);
  135. // see if the type-hint lives in the same namespace as the controller
  136. if (0 === strncmp($type, $class, strrpos($class, '\\'))) {
  137. $message .= ' Did you forget to add a use statement?';
  138. }
  139. throw new InvalidArgumentException($message);
  140. }
  141. $args[$p->name] = $type ? new TypedReference($target, $type, $r->class, $invalidBehavior) : new Reference($target, $invalidBehavior);
  142. }
  143. // register the maps as a per-method service-locators
  144. if ($args) {
  145. $controllers[$id.':'.$r->name] = ServiceLocatorTagPass::register($container, $args);
  146. }
  147. }
  148. }
  149. $container->getDefinition($this->resolverServiceId)
  150. ->replaceArgument(0, ServiceLocatorTagPass::register($container, $controllers));
  151. }
  152. }