RegisterControllerArgumentLocatorsPass.php 7.5 KB

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