RegisterServiceSubscribersPass.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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\DependencyInjection\Compiler;
  11. use Psr\Container\ContainerInterface as PsrContainerInterface;
  12. use Symfony\Component\DependencyInjection\Argument\BoundArgument;
  13. use Symfony\Component\DependencyInjection\ContainerInterface;
  14. use Symfony\Component\DependencyInjection\Definition;
  15. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  16. use Symfony\Component\DependencyInjection\Reference;
  17. use Symfony\Component\DependencyInjection\TypedReference;
  18. use Symfony\Contracts\Service\ServiceProviderInterface;
  19. use Symfony\Contracts\Service\ServiceSubscriberInterface;
  20. /**
  21. * Compiler pass to register tagged services that require a service locator.
  22. *
  23. * @author Nicolas Grekas <p@tchwork.com>
  24. */
  25. class RegisterServiceSubscribersPass extends AbstractRecursivePass
  26. {
  27. protected function processValue($value, bool $isRoot = false)
  28. {
  29. if (!$value instanceof Definition || $value->isAbstract() || $value->isSynthetic() || !$value->hasTag('container.service_subscriber')) {
  30. return parent::processValue($value, $isRoot);
  31. }
  32. $serviceMap = [];
  33. $autowire = $value->isAutowired();
  34. foreach ($value->getTag('container.service_subscriber') as $attributes) {
  35. if (!$attributes) {
  36. $autowire = true;
  37. continue;
  38. }
  39. ksort($attributes);
  40. if ([] !== array_diff(array_keys($attributes), ['id', 'key'])) {
  41. throw new InvalidArgumentException(sprintf('The "container.service_subscriber" tag accepts only the "key" and "id" attributes, "%s" given for service "%s".', implode('", "', array_keys($attributes)), $this->currentId));
  42. }
  43. if (!\array_key_exists('id', $attributes)) {
  44. throw new InvalidArgumentException(sprintf('Missing "id" attribute on "container.service_subscriber" tag with key="%s" for service "%s".', $attributes['key'], $this->currentId));
  45. }
  46. if (!\array_key_exists('key', $attributes)) {
  47. $attributes['key'] = $attributes['id'];
  48. }
  49. if (isset($serviceMap[$attributes['key']])) {
  50. continue;
  51. }
  52. $serviceMap[$attributes['key']] = new Reference($attributes['id']);
  53. }
  54. $class = $value->getClass();
  55. if (!$r = $this->container->getReflectionClass($class)) {
  56. throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $this->currentId));
  57. }
  58. if (!$r->isSubclassOf(ServiceSubscriberInterface::class)) {
  59. throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $this->currentId, ServiceSubscriberInterface::class));
  60. }
  61. $class = $r->name;
  62. $subscriberMap = [];
  63. foreach ($class::getSubscribedServices() as $key => $type) {
  64. if (!\is_string($type) || !preg_match('/^\??[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\\\\[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+$/', $type)) {
  65. throw new InvalidArgumentException(sprintf('"%s::getSubscribedServices()" must return valid PHP types for service "%s" key "%s", "%s" returned.', $class, $this->currentId, $key, \is_string($type) ? $type : get_debug_type($type)));
  66. }
  67. if ($optionalBehavior = '?' === $type[0]) {
  68. $type = substr($type, 1);
  69. $optionalBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  70. }
  71. if (\is_int($name = $key)) {
  72. $key = $type;
  73. $name = null;
  74. }
  75. if (!isset($serviceMap[$key])) {
  76. if (!$autowire) {
  77. throw new InvalidArgumentException(sprintf('Service "%s" misses a "container.service_subscriber" tag with "key"/"id" attributes corresponding to entry "%s" as returned by "%s::getSubscribedServices()".', $this->currentId, $key, $class));
  78. }
  79. $serviceMap[$key] = new Reference($type);
  80. }
  81. if (false !== $i = strpos($name, '::get')) {
  82. $name = lcfirst(substr($name, 5 + $i));
  83. } elseif (false !== strpos($name, '::')) {
  84. $name = null;
  85. }
  86. if (null !== $name && !$this->container->has($name) && !$this->container->has($type.' $'.$name)) {
  87. $camelCaseName = lcfirst(str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $name))));
  88. $name = $this->container->has($type.' $'.$camelCaseName) ? $camelCaseName : $name;
  89. }
  90. $subscriberMap[$key] = new TypedReference((string) $serviceMap[$key], $type, $optionalBehavior ?: ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, $name);
  91. unset($serviceMap[$key]);
  92. }
  93. if ($serviceMap = array_keys($serviceMap)) {
  94. $message = sprintf(1 < \count($serviceMap) ? 'keys "%s" do' : 'key "%s" does', str_replace('%', '%%', implode('", "', $serviceMap)));
  95. throw new InvalidArgumentException(sprintf('Service %s not exist in the map returned by "%s::getSubscribedServices()" for service "%s".', $message, $class, $this->currentId));
  96. }
  97. $locatorRef = ServiceLocatorTagPass::register($this->container, $subscriberMap, $this->currentId);
  98. $value->addTag('container.service_subscriber.locator', ['id' => (string) $locatorRef]);
  99. $value->setBindings([
  100. PsrContainerInterface::class => new BoundArgument($locatorRef, false),
  101. ServiceProviderInterface::class => new BoundArgument($locatorRef, false),
  102. ] + $value->getBindings());
  103. return parent::processValue($value);
  104. }
  105. }