MessengerPass.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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\Messenger\DependencyInjection;
  11. use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
  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\ContainerBuilder;
  16. use Symfony\Component\DependencyInjection\Definition;
  17. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  18. use Symfony\Component\DependencyInjection\Reference;
  19. use Symfony\Component\Messenger\Handler\HandlerDescriptor;
  20. use Symfony\Component\Messenger\Handler\HandlersLocator;
  21. use Symfony\Component\Messenger\Handler\MessageSubscriberInterface;
  22. use Symfony\Component\Messenger\TraceableMessageBus;
  23. use Symfony\Component\Messenger\Transport\Receiver\ReceiverInterface;
  24. /**
  25. * @author Samuel Roze <samuel.roze@gmail.com>
  26. */
  27. class MessengerPass implements CompilerPassInterface
  28. {
  29. private $handlerTag;
  30. private $busTag;
  31. private $receiverTag;
  32. public function __construct(string $handlerTag = 'messenger.message_handler', string $busTag = 'messenger.bus', string $receiverTag = 'messenger.receiver')
  33. {
  34. $this->handlerTag = $handlerTag;
  35. $this->busTag = $busTag;
  36. $this->receiverTag = $receiverTag;
  37. }
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public function process(ContainerBuilder $container)
  42. {
  43. $busIds = [];
  44. foreach ($container->findTaggedServiceIds($this->busTag) as $busId => $tags) {
  45. $busIds[] = $busId;
  46. if ($container->hasParameter($busMiddlewareParameter = $busId.'.middleware')) {
  47. $this->registerBusMiddleware($container, $busId, $container->getParameter($busMiddlewareParameter));
  48. $container->getParameterBag()->remove($busMiddlewareParameter);
  49. }
  50. if ($container->hasDefinition('data_collector.messenger')) {
  51. $this->registerBusToCollector($container, $busId);
  52. }
  53. }
  54. if ($container->hasDefinition('messenger.receiver_locator')) {
  55. $this->registerReceivers($container, $busIds);
  56. }
  57. $this->registerHandlers($container, $busIds);
  58. }
  59. private function registerHandlers(ContainerBuilder $container, array $busIds)
  60. {
  61. $definitions = [];
  62. $handlersByBusAndMessage = [];
  63. $handlerToOriginalServiceIdMapping = [];
  64. foreach ($container->findTaggedServiceIds($this->handlerTag, true) as $serviceId => $tags) {
  65. foreach ($tags as $tag) {
  66. if (isset($tag['bus']) && !\in_array($tag['bus'], $busIds, true)) {
  67. throw new RuntimeException(sprintf('Invalid handler service "%s": bus "%s" specified on the tag "%s" does not exist (known ones are: "%s").', $serviceId, $tag['bus'], $this->handlerTag, implode('", "', $busIds)));
  68. }
  69. $className = $this->getServiceClass($container, $serviceId);
  70. $r = $container->getReflectionClass($className);
  71. if (null === $r) {
  72. throw new RuntimeException(sprintf('Invalid service "%s": class "%s" does not exist.', $serviceId, $className));
  73. }
  74. if (isset($tag['handles'])) {
  75. $handles = isset($tag['method']) ? [$tag['handles'] => $tag['method']] : [$tag['handles']];
  76. } else {
  77. $handles = $this->guessHandledClasses($r, $serviceId);
  78. }
  79. $message = null;
  80. $handlerBuses = (array) ($tag['bus'] ?? $busIds);
  81. foreach ($handles as $message => $options) {
  82. $buses = $handlerBuses;
  83. if (\is_int($message)) {
  84. if (\is_string($options)) {
  85. $message = $options;
  86. $options = [];
  87. } else {
  88. throw new RuntimeException(sprintf('The handler configuration needs to return an array of messages or an associated array of message and configuration. Found value of type "%s" at position "%d" for service "%s".', get_debug_type($options), $message, $serviceId));
  89. }
  90. }
  91. if (\is_string($options)) {
  92. $options = ['method' => $options];
  93. }
  94. if (!isset($options['from_transport']) && isset($tag['from_transport'])) {
  95. $options['from_transport'] = $tag['from_transport'];
  96. }
  97. $priority = $tag['priority'] ?? $options['priority'] ?? 0;
  98. $method = $options['method'] ?? '__invoke';
  99. if (isset($options['bus'])) {
  100. if (!\in_array($options['bus'], $busIds)) {
  101. $messageLocation = isset($tag['handles']) ? 'declared in your tag attribute "handles"' : ($r->implementsInterface(MessageSubscriberInterface::class) ? sprintf('returned by method "%s::getHandledMessages()"', $r->getName()) : sprintf('used as argument type in method "%s::%s()"', $r->getName(), $method));
  102. throw new RuntimeException(sprintf('Invalid configuration %s for message "%s": bus "%s" does not exist.', $messageLocation, $message, $options['bus']));
  103. }
  104. $buses = [$options['bus']];
  105. }
  106. if ('*' !== $message && !class_exists($message) && !interface_exists($message, false)) {
  107. $messageLocation = isset($tag['handles']) ? 'declared in your tag attribute "handles"' : ($r->implementsInterface(MessageSubscriberInterface::class) ? sprintf('returned by method "%s::getHandledMessages()"', $r->getName()) : sprintf('used as argument type in method "%s::%s()"', $r->getName(), $method));
  108. throw new RuntimeException(sprintf('Invalid handler service "%s": class or interface "%s" %s not found.', $serviceId, $message, $messageLocation));
  109. }
  110. if (!$r->hasMethod($method)) {
  111. throw new RuntimeException(sprintf('Invalid handler service "%s": method "%s::%s()" does not exist.', $serviceId, $r->getName(), $method));
  112. }
  113. if ('__invoke' !== $method) {
  114. $wrapperDefinition = (new Definition('callable'))->addArgument([new Reference($serviceId), $method])->setFactory('Closure::fromCallable');
  115. $definitions[$definitionId = '.messenger.method_on_object_wrapper.'.ContainerBuilder::hash($message.':'.$priority.':'.$serviceId.':'.$method)] = $wrapperDefinition;
  116. } else {
  117. $definitionId = $serviceId;
  118. }
  119. $handlerToOriginalServiceIdMapping[$definitionId] = $serviceId;
  120. foreach ($buses as $handlerBus) {
  121. $handlersByBusAndMessage[$handlerBus][$message][$priority][] = [$definitionId, $options];
  122. }
  123. }
  124. if (null === $message) {
  125. throw new RuntimeException(sprintf('Invalid handler service "%s": method "%s::getHandledMessages()" must return one or more messages.', $serviceId, $r->getName()));
  126. }
  127. }
  128. }
  129. foreach ($handlersByBusAndMessage as $bus => $handlersByMessage) {
  130. foreach ($handlersByMessage as $message => $handlersByPriority) {
  131. krsort($handlersByPriority);
  132. $handlersByBusAndMessage[$bus][$message] = array_merge(...$handlersByPriority);
  133. }
  134. }
  135. $handlersLocatorMappingByBus = [];
  136. foreach ($handlersByBusAndMessage as $bus => $handlersByMessage) {
  137. foreach ($handlersByMessage as $message => $handlers) {
  138. $handlerDescriptors = [];
  139. foreach ($handlers as $handler) {
  140. $definitions[$definitionId = '.messenger.handler_descriptor.'.ContainerBuilder::hash($bus.':'.$message.':'.$handler[0])] = (new Definition(HandlerDescriptor::class))->setArguments([new Reference($handler[0]), $handler[1]]);
  141. $handlerDescriptors[] = new Reference($definitionId);
  142. }
  143. $handlersLocatorMappingByBus[$bus][$message] = new IteratorArgument($handlerDescriptors);
  144. }
  145. }
  146. $container->addDefinitions($definitions);
  147. foreach ($busIds as $bus) {
  148. $container->register($locatorId = $bus.'.messenger.handlers_locator', HandlersLocator::class)
  149. ->setArgument(0, $handlersLocatorMappingByBus[$bus] ?? [])
  150. ;
  151. if ($container->has($handleMessageId = $bus.'.middleware.handle_message')) {
  152. $container->getDefinition($handleMessageId)
  153. ->replaceArgument(0, new Reference($locatorId))
  154. ;
  155. }
  156. }
  157. if ($container->hasDefinition('console.command.messenger_debug')) {
  158. $debugCommandMapping = $handlersByBusAndMessage;
  159. foreach ($busIds as $bus) {
  160. if (!isset($debugCommandMapping[$bus])) {
  161. $debugCommandMapping[$bus] = [];
  162. }
  163. foreach ($debugCommandMapping[$bus] as $message => $handlers) {
  164. foreach ($handlers as $key => $handler) {
  165. $debugCommandMapping[$bus][$message][$key][0] = $handlerToOriginalServiceIdMapping[$handler[0]];
  166. }
  167. }
  168. }
  169. $container->getDefinition('console.command.messenger_debug')->replaceArgument(0, $debugCommandMapping);
  170. }
  171. }
  172. private function guessHandledClasses(\ReflectionClass $handlerClass, string $serviceId): iterable
  173. {
  174. if ($handlerClass->implementsInterface(MessageSubscriberInterface::class)) {
  175. return $handlerClass->getName()::getHandledMessages();
  176. }
  177. try {
  178. $method = $handlerClass->getMethod('__invoke');
  179. } catch (\ReflectionException $e) {
  180. throw new RuntimeException(sprintf('Invalid handler service "%s": class "%s" must have an "__invoke()" method.', $serviceId, $handlerClass->getName()));
  181. }
  182. if (0 === $method->getNumberOfRequiredParameters()) {
  183. throw new RuntimeException(sprintf('Invalid handler service "%s": method "%s::__invoke()" requires at least one argument, first one being the message it handles.', $serviceId, $handlerClass->getName()));
  184. }
  185. $parameters = $method->getParameters();
  186. if (!$type = $parameters[0]->getType()) {
  187. throw new RuntimeException(sprintf('Invalid handler service "%s": argument "$%s" of method "%s::__invoke()" must have a type-hint corresponding to the message class it handles.', $serviceId, $parameters[0]->getName(), $handlerClass->getName()));
  188. }
  189. if ($type instanceof \ReflectionUnionType) {
  190. $types = [];
  191. foreach ($type->getTypes() as $type) {
  192. if (!$type->isBuiltin()) {
  193. $types[] = (string) $type;
  194. }
  195. }
  196. if ($types) {
  197. return $types;
  198. }
  199. }
  200. if ($type->isBuiltin()) {
  201. throw new RuntimeException(sprintf('Invalid handler service "%s": type-hint of argument "$%s" in method "%s::__invoke()" must be a class , "%s" given.', $serviceId, $parameters[0]->getName(), $handlerClass->getName(), $type instanceof \ReflectionNamedType ? $type->getName() : (string) $type));
  202. }
  203. return [$type->getName()];
  204. }
  205. private function registerReceivers(ContainerBuilder $container, array $busIds)
  206. {
  207. $receiverMapping = [];
  208. foreach ($container->findTaggedServiceIds($this->receiverTag) as $id => $tags) {
  209. $receiverClass = $this->getServiceClass($container, $id);
  210. if (!is_subclass_of($receiverClass, ReceiverInterface::class)) {
  211. throw new RuntimeException(sprintf('Invalid receiver "%s": class "%s" must implement interface "%s".', $id, $receiverClass, ReceiverInterface::class));
  212. }
  213. $receiverMapping[$id] = new Reference($id);
  214. foreach ($tags as $tag) {
  215. if (isset($tag['alias'])) {
  216. $receiverMapping[$tag['alias']] = $receiverMapping[$id];
  217. }
  218. }
  219. }
  220. $receiverNames = [];
  221. foreach ($receiverMapping as $name => $reference) {
  222. $receiverNames[(string) $reference] = $name;
  223. }
  224. $buses = [];
  225. foreach ($busIds as $busId) {
  226. $buses[$busId] = new Reference($busId);
  227. }
  228. if ($hasRoutableMessageBus = $container->hasDefinition('messenger.routable_message_bus')) {
  229. $container->getDefinition('messenger.routable_message_bus')
  230. ->replaceArgument(0, ServiceLocatorTagPass::register($container, $buses));
  231. }
  232. if ($container->hasDefinition('console.command.messenger_consume_messages')) {
  233. $consumeCommandDefinition = $container->getDefinition('console.command.messenger_consume_messages');
  234. if ($hasRoutableMessageBus) {
  235. $consumeCommandDefinition->replaceArgument(0, new Reference('messenger.routable_message_bus'));
  236. }
  237. $consumeCommandDefinition->replaceArgument(4, array_values($receiverNames));
  238. }
  239. if ($container->hasDefinition('console.command.messenger_setup_transports')) {
  240. $container->getDefinition('console.command.messenger_setup_transports')
  241. ->replaceArgument(1, array_values($receiverNames));
  242. }
  243. $container->getDefinition('messenger.receiver_locator')->replaceArgument(0, $receiverMapping);
  244. $failedCommandIds = [
  245. 'console.command.messenger_failed_messages_retry',
  246. 'console.command.messenger_failed_messages_show',
  247. 'console.command.messenger_failed_messages_remove',
  248. ];
  249. foreach ($failedCommandIds as $failedCommandId) {
  250. if ($container->hasDefinition($failedCommandId)) {
  251. $definition = $container->getDefinition($failedCommandId);
  252. $definition->replaceArgument(1, $receiverMapping[$definition->getArgument(0)]);
  253. }
  254. }
  255. }
  256. private function registerBusToCollector(ContainerBuilder $container, string $busId)
  257. {
  258. $container->setDefinition(
  259. $tracedBusId = 'debug.traced.'.$busId,
  260. (new Definition(TraceableMessageBus::class, [new Reference($tracedBusId.'.inner')]))->setDecoratedService($busId)
  261. );
  262. $container->getDefinition('data_collector.messenger')->addMethodCall('registerBus', [$busId, new Reference($tracedBusId)]);
  263. }
  264. private function registerBusMiddleware(ContainerBuilder $container, string $busId, array $middlewareCollection)
  265. {
  266. $middlewareReferences = [];
  267. foreach ($middlewareCollection as $middlewareItem) {
  268. $id = $middlewareItem['id'];
  269. $arguments = $middlewareItem['arguments'] ?? [];
  270. if (!$container->has($messengerMiddlewareId = 'messenger.middleware.'.$id)) {
  271. $messengerMiddlewareId = $id;
  272. }
  273. if (!$container->has($messengerMiddlewareId)) {
  274. throw new RuntimeException(sprintf('Invalid middleware: service "%s" not found.', $id));
  275. }
  276. if ($container->findDefinition($messengerMiddlewareId)->isAbstract()) {
  277. $childDefinition = new ChildDefinition($messengerMiddlewareId);
  278. $childDefinition->setArguments($arguments);
  279. if (isset($middlewareReferences[$messengerMiddlewareId = $busId.'.middleware.'.$id])) {
  280. $messengerMiddlewareId .= '.'.ContainerBuilder::hash($arguments);
  281. }
  282. $container->setDefinition($messengerMiddlewareId, $childDefinition);
  283. } elseif ($arguments) {
  284. throw new RuntimeException(sprintf('Invalid middleware factory "%s": a middleware factory must be an abstract definition.', $id));
  285. }
  286. $middlewareReferences[$messengerMiddlewareId] = new Reference($messengerMiddlewareId);
  287. }
  288. $container->getDefinition($busId)->replaceArgument(0, new IteratorArgument(array_values($middlewareReferences)));
  289. }
  290. private function getServiceClass(ContainerBuilder $container, string $serviceId): string
  291. {
  292. while (true) {
  293. $definition = $container->findDefinition($serviceId);
  294. if (!$definition->getClass() && $definition instanceof ChildDefinition) {
  295. $serviceId = $definition->getParent();
  296. continue;
  297. }
  298. return $definition->getClass();
  299. }
  300. }
  301. }