From ee8e82f8f91604ee18bf53191013d4b95b2d2b81 Mon Sep 17 00:00:00 2001 From: "Roland Franssen :)" Date: Wed, 11 Jun 2025 10:44:40 +0200 Subject: [PATCH 1/5] [Messenger] Fix float value for worker memory limit --- Command/ConsumeMessagesCommand.php | 4 +- Tests/Command/ConsumeMessagesCommandTest.php | 46 ++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/Command/ConsumeMessagesCommand.php b/Command/ConsumeMessagesCommand.php index 7aa8752f..61fe6d9b 100644 --- a/Command/ConsumeMessagesCommand.php +++ b/Command/ConsumeMessagesCommand.php @@ -289,7 +289,7 @@ private function convertToBytes(string $memoryLimit): int } elseif (str_starts_with($max, '0')) { $max = \intval($max, 8); } else { - $max = (int) $max; + $max = (float) $max; } switch (substr(rtrim($memoryLimit, 'b'), -1)) { @@ -302,6 +302,6 @@ private function convertToBytes(string $memoryLimit): int case 'k': $max *= 1024; } - return $max; + return (int) $max; } } diff --git a/Tests/Command/ConsumeMessagesCommandTest.php b/Tests/Command/ConsumeMessagesCommandTest.php index 4ff6b66d..1a42005c 100644 --- a/Tests/Command/ConsumeMessagesCommandTest.php +++ b/Tests/Command/ConsumeMessagesCommandTest.php @@ -12,6 +12,8 @@ namespace Symfony\Component\Messenger\Tests\Command; use PHPUnit\Framework\TestCase; +use Psr\Log\LoggerInterface; +use Psr\Log\LoggerTrait; use Symfony\Component\Console\Application; use Symfony\Component\Console\Exception\InvalidOptionException; use Symfony\Component\Console\Tester\CommandCompletionTester; @@ -214,6 +216,50 @@ public function testRunWithTimeLimit() $this->assertStringContainsString('[OK] Consuming messages from transport "dummy-receiver"', $tester->getDisplay()); } + public function testRunWithMemoryLimit() + { + $envelope = new Envelope(new \stdClass(), [new BusNameStamp('dummy-bus')]); + + $receiver = $this->createMock(ReceiverInterface::class); + $receiver->method('get')->willReturn([$envelope]); + + $receiverLocator = $this->createMock(ContainerInterface::class); + $receiverLocator->method('has')->with('dummy-receiver')->willReturn(true); + $receiverLocator->method('get')->with('dummy-receiver')->willReturn($receiver); + + $bus = $this->createMock(MessageBusInterface::class); + + $busLocator = $this->createMock(ContainerInterface::class); + $busLocator->method('has')->with('dummy-bus')->willReturn(true); + $busLocator->method('get')->with('dummy-bus')->willReturn($bus); + + $logger = new class() implements LoggerInterface { + use LoggerTrait; + + public array $logs = []; + + public function log(...$args): void + { + $this->logs[] = $args; + } + }; + $command = new ConsumeMessagesCommand(new RoutableMessageBus($busLocator), $receiverLocator, new EventDispatcher(), $logger); + + $application = new Application(); + $application->add($command); + $tester = new CommandTester($application->get('messenger:consume')); + $tester->execute([ + 'receivers' => ['dummy-receiver'], + '--memory-limit' => '1.5M', + ]); + + $this->assertSame(0, $tester->getStatusCode()); + $this->assertStringContainsString('[OK] Consuming messages from transport "dummy-receiver"', $tester->getDisplay()); + $this->assertStringContainsString('The worker will automatically exit once it has exceeded 1.5M of memory', $tester->getDisplay()); + + $this->assertSame(1572864, $logger->logs[1][2]['limit']); + } + /** * @dataProvider provideCompletionSuggestions */ From e6f6131251be2be5ca8438ba9ea0dab160fcf4a8 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Mon, 16 Jun 2025 09:56:14 +0200 Subject: [PATCH 2/5] [Messenger] Fix merge --- Tests/Command/ConsumeMessagesCommandTest.php | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/Tests/Command/ConsumeMessagesCommandTest.php b/Tests/Command/ConsumeMessagesCommandTest.php index a3cd36ca..7183f2e7 100644 --- a/Tests/Command/ConsumeMessagesCommandTest.php +++ b/Tests/Command/ConsumeMessagesCommandTest.php @@ -214,15 +214,13 @@ public function testRunWithMemoryLimit() $receiver = $this->createMock(ReceiverInterface::class); $receiver->method('get')->willReturn([$envelope]); - $receiverLocator = $this->createMock(ContainerInterface::class); - $receiverLocator->method('has')->with('dummy-receiver')->willReturn(true); - $receiverLocator->method('get')->with('dummy-receiver')->willReturn($receiver); + $receiverLocator = new Container(); + $receiverLocator->set('dummy-receiver', $receiver); $bus = $this->createMock(MessageBusInterface::class); - $busLocator = $this->createMock(ContainerInterface::class); - $busLocator->method('has')->with('dummy-bus')->willReturn(true); - $busLocator->method('get')->with('dummy-bus')->willReturn($bus); + $busLocator = new Container(); + $busLocator->set('dummy-bus', $bus); $logger = new class() implements LoggerInterface { use LoggerTrait; @@ -249,6 +247,7 @@ public function log(...$args): void $this->assertStringContainsString('The worker will automatically exit once it has exceeded 1.5M of memory', $tester->getDisplay()); $this->assertSame(1572864, $logger->logs[1][2]['limit']); + } public function testRunWithAllOption() { From 862d99460cd12a1e6cc2ef928b06ec4bae47d39f Mon Sep 17 00:00:00 2001 From: Gregor Harlan Date: Thu, 26 Jun 2025 22:46:07 +0200 Subject: [PATCH 3/5] Fix command option mode (InputOption::VALUE_REQUIRED) --- Command/FailedMessagesRemoveCommand.php | 2 +- Command/FailedMessagesRetryCommand.php | 2 +- Command/FailedMessagesShowCommand.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Command/FailedMessagesRemoveCommand.php b/Command/FailedMessagesRemoveCommand.php index 09d8e898..d21e2614 100644 --- a/Command/FailedMessagesRemoveCommand.php +++ b/Command/FailedMessagesRemoveCommand.php @@ -35,7 +35,7 @@ protected function configure(): void new InputArgument('id', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, 'Specific message id(s) to remove'), new InputOption('all', null, InputOption::VALUE_NONE, 'Remove all failed messages from the transport'), new InputOption('force', null, InputOption::VALUE_NONE, 'Force the operation without confirmation'), - new InputOption('transport', null, InputOption::VALUE_OPTIONAL, 'Use a specific failure transport', self::DEFAULT_TRANSPORT_OPTION), + new InputOption('transport', null, InputOption::VALUE_REQUIRED, 'Use a specific failure transport', self::DEFAULT_TRANSPORT_OPTION), new InputOption('show-messages', null, InputOption::VALUE_NONE, 'Display messages before removing it (if multiple ids are given)'), ]) ->setHelp(<<<'EOF' diff --git a/Command/FailedMessagesRetryCommand.php b/Command/FailedMessagesRetryCommand.php index 677743c9..c7082419 100644 --- a/Command/FailedMessagesRetryCommand.php +++ b/Command/FailedMessagesRetryCommand.php @@ -63,7 +63,7 @@ protected function configure(): void ->setDefinition([ new InputArgument('id', InputArgument::IS_ARRAY, 'Specific message id(s) to retry'), new InputOption('force', null, InputOption::VALUE_NONE, 'Force action without confirmation'), - new InputOption('transport', null, InputOption::VALUE_OPTIONAL, 'Use a specific failure transport', self::DEFAULT_TRANSPORT_OPTION), + new InputOption('transport', null, InputOption::VALUE_REQUIRED, 'Use a specific failure transport', self::DEFAULT_TRANSPORT_OPTION), ]) ->setHelp(<<<'EOF' The %command.name% retries message in the failure transport. diff --git a/Command/FailedMessagesShowCommand.php b/Command/FailedMessagesShowCommand.php index 25fb9a8d..36369961 100644 --- a/Command/FailedMessagesShowCommand.php +++ b/Command/FailedMessagesShowCommand.php @@ -35,7 +35,7 @@ protected function configure(): void ->setDefinition([ new InputArgument('id', InputArgument::OPTIONAL, 'Specific message id to show'), new InputOption('max', null, InputOption::VALUE_REQUIRED, 'Maximum number of messages to list', 50), - new InputOption('transport', null, InputOption::VALUE_OPTIONAL, 'Use a specific failure transport', self::DEFAULT_TRANSPORT_OPTION), + new InputOption('transport', null, InputOption::VALUE_REQUIRED, 'Use a specific failure transport', self::DEFAULT_TRANSPORT_OPTION), new InputOption('stats', null, InputOption::VALUE_NONE, 'Display the message count by class'), new InputOption('class-filter', null, InputOption::VALUE_REQUIRED, 'Filter by a specific class name'), ]) From 74cfff2d0df017c21afedb01edd0479ed56d9d13 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Thu, 10 Jul 2025 09:12:18 +0200 Subject: [PATCH 4/5] CS fixes --- Command/AbstractFailedMessagesCommand.php | 12 +++---- Command/ConsumeMessagesCommand.php | 12 +++---- Command/DebugCommand.php | 14 ++++---- Command/FailedMessagesRemoveCommand.php | 12 +++---- Command/FailedMessagesRetryCommand.php | 8 ++--- Command/FailedMessagesShowCommand.php | 16 ++++----- Command/SetupTransportsCommand.php | 8 ++--- Command/StatsCommand.php | 4 +-- DependencyInjection/MessengerPass.php | 36 +++++++++---------- .../SendFailedMessageForRetryListener.php | 2 +- Exception/DelayedMessageHandlingException.php | 4 +-- Exception/HandlerFailedException.php | 4 +-- Exception/ValidationFailedException.php | 2 +- HandleTrait.php | 8 ++--- Handler/Acknowledger.php | 4 +-- Message/RedispatchMessage.php | 2 +- Middleware/HandleMessageMiddleware.php | 4 +-- Middleware/SendMessageMiddleware.php | 2 +- Middleware/TraceableMiddleware.php | 4 +-- Retry/MultiplierRetryStrategy.php | 6 ++-- RoutableMessageBus.php | 2 +- Tests/Command/ConsumeMessagesCommandTest.php | 2 +- .../DependencyInjection/MessengerPassTest.php | 6 ++-- ...orkerOnCustomStopExceptionListenerTest.php | 2 +- .../Exception/HandlerFailedExceptionTest.php | 2 +- Tests/Handler/HandleDescriptorTest.php | 2 +- .../HandleMessageMiddlewareTest.php | 14 ++++---- Tests/Middleware/TraceableMiddlewareTest.php | 2 +- .../Serialization/SerializerTest.php | 3 +- Transport/InMemory/InMemoryTransport.php | 2 +- Transport/Sender/SendersLocator.php | 2 +- Transport/Serialization/PhpSerializer.php | 2 +- Transport/Serialization/Serializer.php | 2 +- 33 files changed, 103 insertions(+), 104 deletions(-) diff --git a/Command/AbstractFailedMessagesCommand.php b/Command/AbstractFailedMessagesCommand.php index e5f6ae92..f20de25f 100644 --- a/Command/AbstractFailedMessagesCommand.php +++ b/Command/AbstractFailedMessagesCommand.php @@ -126,7 +126,7 @@ protected function displaySingleMessage(Envelope $envelope, SymfonyStyle $io): v $redeliveryStamps = $envelope->all(RedeliveryStamp::class); $io->writeln(' Message history:'); foreach ($redeliveryStamps as $redeliveryStamp) { - $io->writeln(sprintf(' * Message failed at %s and was redelivered', $redeliveryStamp->getRedeliveredAt()->format('Y-m-d H:i:s'))); + $io->writeln(\sprintf(' * Message failed at %s and was redelivered', $redeliveryStamp->getRedeliveredAt()->format('Y-m-d H:i:s'))); } $io->newLine(); @@ -154,7 +154,7 @@ protected function printPendingMessagesMessage(ReceiverInterface $receiver, Symf if (1 === $receiver->getMessageCount()) { $io->writeln('There is 1 message pending in the failure transport.'); } else { - $io->writeln(sprintf('There are %d messages pending in the failure transport.', $receiver->getMessageCount())); + $io->writeln(\sprintf('There are %d messages pending in the failure transport.', $receiver->getMessageCount())); } } } @@ -162,11 +162,11 @@ protected function printPendingMessagesMessage(ReceiverInterface $receiver, Symf protected function getReceiver(?string $name = null): ReceiverInterface { if (null === $name ??= $this->globalFailureReceiverName) { - throw new InvalidArgumentException(sprintf('No default failure transport is defined. Available transports are: "%s".', implode('", "', array_keys($this->failureTransports->getProvidedServices())))); + throw new InvalidArgumentException(\sprintf('No default failure transport is defined. Available transports are: "%s".', implode('", "', array_keys($this->failureTransports->getProvidedServices())))); } if (!$this->failureTransports->has($name)) { - throw new InvalidArgumentException(sprintf('The "%s" failure transport was not found. Available transports are: "%s".', $name, implode('", "', array_keys($this->failureTransports->getProvidedServices())))); + throw new InvalidArgumentException(\sprintf('The "%s" failure transport was not found. Available transports are: "%s".', $name, implode('", "', array_keys($this->failureTransports->getProvidedServices())))); } return $this->failureTransports->get($name); @@ -200,9 +200,9 @@ protected function printWarningAvailableFailureTransports(SymfonyStyle $io, ?str $failureTransportsCount = \count($failureTransports); if ($failureTransportsCount > 1) { $io->writeln([ - sprintf('> Loading messages from the global failure transport %s.', $failureTransportName), + \sprintf('> Loading messages from the global failure transport %s.', $failureTransportName), '> To use a different failure transport, pass --transport=.', - sprintf('> Available failure transports are: %s', implode(', ', $failureTransports)), + \sprintf('> Available failure transports are: %s', implode(', ', $failureTransports)), "\n", ]); } diff --git a/Command/ConsumeMessagesCommand.php b/Command/ConsumeMessagesCommand.php index 61fe6d9b..28c84419 100644 --- a/Command/ConsumeMessagesCommand.php +++ b/Command/ConsumeMessagesCommand.php @@ -146,7 +146,7 @@ protected function interact(InputInterface $input, OutputInterface $output) $io->writeln('Choose which receivers you want to consume messages from in order of priority.'); if (\count($this->receiverNames) > 1) { - $io->writeln(sprintf('Hint: to consume from multiple, use a list of their names, e.g. %s', implode(', ', $this->receiverNames))); + $io->writeln(\sprintf('Hint: to consume from multiple, use a list of their names, e.g. %s', implode(', ', $this->receiverNames))); } $question = new ChoiceQuestion('Select receivers to consume:', $this->receiverNames, 0); @@ -166,9 +166,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int $rateLimiters = []; foreach ($receiverNames = $input->getArgument('receivers') as $receiverName) { if (!$this->receiverLocator->has($receiverName)) { - $message = sprintf('The receiver "%s" does not exist.', $receiverName); + $message = \sprintf('The receiver "%s" does not exist.', $receiverName); if ($this->receiverNames) { - $message .= sprintf(' Valid receivers are: %s.', implode(', ', $this->receiverNames)); + $message .= \sprintf(' Valid receivers are: %s.', implode(', ', $this->receiverNames)); } throw new RuntimeException($message); @@ -187,7 +187,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $stopsWhen = []; if (null !== $limit = $input->getOption('limit')) { if (!is_numeric($limit) || 0 >= $limit) { - throw new InvalidOptionException(sprintf('Option "limit" must be a positive integer, "%s" passed.', $limit)); + throw new InvalidOptionException(\sprintf('Option "limit" must be a positive integer, "%s" passed.', $limit)); } $stopsWhen[] = "processed {$limit} messages"; @@ -206,7 +206,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if (null !== $timeLimit = $input->getOption('time-limit')) { if (!is_numeric($timeLimit) || 0 >= $timeLimit) { - throw new InvalidOptionException(sprintf('Option "time-limit" must be a positive integer, "%s" passed.', $timeLimit)); + throw new InvalidOptionException(\sprintf('Option "time-limit" must be a positive integer, "%s" passed.', $timeLimit)); } $stopsWhen[] = "been running for {$timeLimit}s"; @@ -216,7 +216,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $stopsWhen[] = 'received a stop signal via the messenger:stop-workers command'; $io = new SymfonyStyle($input, $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output); - $io->success(sprintf('Consuming messages from transport%s "%s".', \count($receivers) > 1 ? 's' : '', implode(', ', $receiverNames))); + $io->success(\sprintf('Consuming messages from transport%s "%s".', \count($receivers) > 1 ? 's' : '', implode(', ', $receiverNames))); if ($stopsWhen) { $last = array_pop($stopsWhen); diff --git a/Command/DebugCommand.php b/Command/DebugCommand.php index 5767f06a..ef536ccd 100644 --- a/Command/DebugCommand.php +++ b/Command/DebugCommand.php @@ -44,7 +44,7 @@ public function __construct(array $mapping) protected function configure() { $this - ->addArgument('bus', InputArgument::OPTIONAL, sprintf('The bus id (one of "%s")', implode('", "', array_keys($this->mapping)))) + ->addArgument('bus', InputArgument::OPTIONAL, \sprintf('The bus id (one of "%s")', implode('", "', array_keys($this->mapping)))) ->setHelp(<<<'EOF' The %command.name% command displays all messages that can be dispatched using the message buses: @@ -68,7 +68,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $mapping = $this->mapping; if ($bus = $input->getArgument('bus')) { if (!isset($mapping[$bus])) { - throw new RuntimeException(sprintf('Bus "%s" does not exist. Known buses are "%s".', $bus, implode('", "', array_keys($this->mapping)))); + throw new RuntimeException(\sprintf('Bus "%s" does not exist. Known buses are "%s".', $bus, implode('", "', array_keys($this->mapping)))); } $mapping = [$bus => $mapping[$bus]]; } @@ -79,16 +79,16 @@ protected function execute(InputInterface $input, OutputInterface $output): int $tableRows = []; foreach ($handlersByMessage as $message => $handlers) { if ($description = self::getClassDescription($message)) { - $tableRows[] = [sprintf('%s', $description)]; + $tableRows[] = [\sprintf('%s', $description)]; } - $tableRows[] = [sprintf('%s', $message)]; + $tableRows[] = [\sprintf('%s', $message)]; foreach ($handlers as $handler) { $tableRows[] = [ - sprintf(' handled by %s', $handler[0]).$this->formatConditions($handler[1]), + \sprintf(' handled by %s', $handler[0]).$this->formatConditions($handler[1]), ]; if ($handlerDescription = self::getClassDescription($handler[0])) { - $tableRows[] = [sprintf(' %s', $handlerDescription)]; + $tableRows[] = [\sprintf(' %s', $handlerDescription)]; } } $tableRows[] = ['']; @@ -99,7 +99,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $io->newLine(); $io->table([], $tableRows); } else { - $io->warning(sprintf('No handled message found in bus "%s".', $bus)); + $io->warning(\sprintf('No handled message found in bus "%s".', $bus)); } } diff --git a/Command/FailedMessagesRemoveCommand.php b/Command/FailedMessagesRemoveCommand.php index d21e2614..648060a6 100644 --- a/Command/FailedMessagesRemoveCommand.php +++ b/Command/FailedMessagesRemoveCommand.php @@ -78,7 +78,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $shouldDisplayMessages = $input->getOption('show-messages') || 1 === $idsCount; if (!$receiver instanceof ListableReceiverInterface) { - throw new RuntimeException(sprintf('The "%s" receiver does not support removing specific messages.', $failureTransportName)); + throw new RuntimeException(\sprintf('The "%s" receiver does not support removing specific messages.', $failureTransportName)); } if ($shouldDeleteAllMessages) { @@ -101,7 +101,7 @@ private function removeMessagesById(array $ids, ListableReceiverInterface $recei } if (null === $envelope) { - $io->error(sprintf('The message with id "%s" was not found.', $id)); + $io->error(\sprintf('The message with id "%s" was not found.', $id)); continue; } @@ -112,9 +112,9 @@ private function removeMessagesById(array $ids, ListableReceiverInterface $recei if ($shouldForce || $io->confirm('Do you want to permanently remove this message?', false)) { $receiver->reject($envelope); - $io->success(sprintf('Message with id %s removed.', $id)); + $io->success(\sprintf('Message with id %s removed.', $id)); } else { - $io->note(sprintf('Message with id %s not removed.', $id)); + $io->note(\sprintf('Message with id %s not removed.', $id)); } } } @@ -123,7 +123,7 @@ private function removeAllMessages(ListableReceiverInterface $receiver, SymfonyS { if (!$shouldForce) { if ($receiver instanceof MessageCountAwareInterface) { - $question = sprintf('Do you want to permanently remove all (%d) messages?', $receiver->getMessageCount()); + $question = \sprintf('Do you want to permanently remove all (%d) messages?', $receiver->getMessageCount()); } else { $question = 'Do you want to permanently remove all failed messages?'; } @@ -143,6 +143,6 @@ private function removeAllMessages(ListableReceiverInterface $receiver, SymfonyS ++$count; } - $io->note(sprintf('%d messages were removed.', $count)); + $io->note(\sprintf('%d messages were removed.', $count)); } } diff --git a/Command/FailedMessagesRetryCommand.php b/Command/FailedMessagesRetryCommand.php index c7082419..59a9d253 100644 --- a/Command/FailedMessagesRetryCommand.php +++ b/Command/FailedMessagesRetryCommand.php @@ -109,7 +109,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $receiver = $this->getReceiver($failureTransportName); $this->printPendingMessagesMessage($receiver, $io); - $io->writeln(sprintf('To retry all the messages, run messenger:consume %s', $failureTransportName)); + $io->writeln(\sprintf('To retry all the messages, run messenger:consume %s', $failureTransportName)); $shouldForce = $input->getOption('force'); $ids = $input->getArgument('id'); @@ -201,7 +201,7 @@ private function runWorker(string $failureTransportName, ReceiverInterface $rece $this->displaySingleMessage($envelope, $io); if ($envelope->last(MessageDecodingFailedStamp::class)) { - throw new \RuntimeException(sprintf('The message with id "%s" could not decoded, it can only be shown or removed.', $this->getMessageId($envelope) ?? '?')); + throw new \RuntimeException(\sprintf('The message with id "%s" could not decoded, it can only be shown or removed.', $this->getMessageId($envelope) ?? '?')); } $this->forceExit = true; @@ -242,7 +242,7 @@ private function retrySpecificIds(string $failureTransportName, array $ids, Symf $receiver = $this->getReceiver($failureTransportName); if (!$receiver instanceof ListableReceiverInterface) { - throw new RuntimeException(sprintf('The "%s" receiver does not support retrying messages by id.', $failureTransportName)); + throw new RuntimeException(\sprintf('The "%s" receiver does not support retrying messages by id.', $failureTransportName)); } foreach ($ids as $id) { @@ -253,7 +253,7 @@ private function retrySpecificIds(string $failureTransportName, array $ids, Symf $this->phpSerializer?->rejectPhpIncompleteClass(); } if (null === $envelope) { - throw new RuntimeException(sprintf('The message "%s" was not found.', $id)); + throw new RuntimeException(\sprintf('The message "%s" was not found.', $id)); } $singleReceiver = new SingleMessageReceiver($receiver, $envelope); diff --git a/Command/FailedMessagesShowCommand.php b/Command/FailedMessagesShowCommand.php index 36369961..927e6705 100644 --- a/Command/FailedMessagesShowCommand.php +++ b/Command/FailedMessagesShowCommand.php @@ -70,7 +70,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->printPendingMessagesMessage($receiver, $io); if (!$receiver instanceof ListableReceiverInterface) { - throw new RuntimeException(sprintf('The "%s" receiver does not support listing or showing specific messages.', $failureTransportName)); + throw new RuntimeException(\sprintf('The "%s" receiver does not support listing or showing specific messages.', $failureTransportName)); } if ($input->getOption('stats')) { @@ -93,7 +93,7 @@ private function listMessages(?string $failedTransportName, SymfonyStyle $io, in $rows = []; if ($classFilter) { - $io->comment(sprintf('Displaying only \'%s\' messages', $classFilter)); + $io->comment(\sprintf('Displaying only \'%s\' messages', $classFilter)); } $this->phpSerializer?->acceptPhpIncompleteClass(); @@ -132,12 +132,12 @@ private function listMessages(?string $failedTransportName, SymfonyStyle $io, in $io->table(['Id', 'Class', 'Failed at', 'Error'], $rows); if ($rowsCount === $max) { - $io->comment(sprintf('Showing first %d messages.', $max)); + $io->comment(\sprintf('Showing first %d messages.', $max)); } elseif ($classFilter) { - $io->comment(sprintf('Showing %d message(s).', $rowsCount)); + $io->comment(\sprintf('Showing %d message(s).', $rowsCount)); } - $io->comment(sprintf('Run messenger:failed:show {id} --transport=%s -vv to see message details.', $failedTransportName)); + $io->comment(\sprintf('Run messenger:failed:show {id} --transport=%s -vv to see message details.', $failedTransportName)); } private function listMessagesPerClass(?string $failedTransportName, SymfonyStyle $io, int $max): void @@ -183,15 +183,15 @@ private function showMessage(?string $failedTransportName, string $id, SymfonySt $this->phpSerializer?->rejectPhpIncompleteClass(); } if (null === $envelope) { - throw new RuntimeException(sprintf('The message "%s" was not found.', $id)); + throw new RuntimeException(\sprintf('The message "%s" was not found.', $id)); } $this->displaySingleMessage($envelope, $io); $io->writeln([ '', - sprintf(' Run messenger:failed:retry %s --transport=%s to retry this message.', $id, $failedTransportName), - sprintf(' Run messenger:failed:remove %s --transport=%s to delete it.', $id, $failedTransportName), + \sprintf(' Run messenger:failed:retry %s --transport=%s to retry this message.', $id, $failedTransportName), + \sprintf(' Run messenger:failed:remove %s --transport=%s to delete it.', $id, $failedTransportName), ]); } } diff --git a/Command/SetupTransportsCommand.php b/Command/SetupTransportsCommand.php index 43447633..0082a597 100644 --- a/Command/SetupTransportsCommand.php +++ b/Command/SetupTransportsCommand.php @@ -67,7 +67,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int // do we want to set up only one transport? if ($transport = $input->getArgument('transport')) { if (!$this->transportLocator->has($transport)) { - throw new \RuntimeException(sprintf('The "%s" transport does not exist.', $transport)); + throw new \RuntimeException(\sprintf('The "%s" transport does not exist.', $transport)); } $transportNames = [$transport]; } @@ -75,15 +75,15 @@ protected function execute(InputInterface $input, OutputInterface $output): int foreach ($transportNames as $id => $transportName) { $transport = $this->transportLocator->get($transportName); if (!$transport instanceof SetupableTransportInterface) { - $io->note(sprintf('The "%s" transport does not support setup.', $transportName)); + $io->note(\sprintf('The "%s" transport does not support setup.', $transportName)); continue; } try { $transport->setup(); - $io->success(sprintf('The "%s" transport was set up successfully.', $transportName)); + $io->success(\sprintf('The "%s" transport was set up successfully.', $transportName)); } catch (\Exception $e) { - throw new \RuntimeException(sprintf('An error occurred while setting up the "%s" transport: ', $transportName).$e->getMessage(), 0, $e); + throw new \RuntimeException(\sprintf('An error occurred while setting up the "%s" transport: ', $transportName).$e->getMessage(), 0, $e); } } diff --git a/Command/StatsCommand.php b/Command/StatsCommand.php index 3b6d6b8a..107ef5bb 100644 --- a/Command/StatsCommand.php +++ b/Command/StatsCommand.php @@ -71,7 +71,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $uncountableTransports = []; foreach ($transportNames as $transportName) { if (!$this->transportLocator->has($transportName)) { - $io->warning(sprintf('The "%s" transport does not exist.', $transportName)); + $io->warning(\sprintf('The "%s" transport does not exist.', $transportName)); continue; } @@ -87,7 +87,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $io->table(['Transport', 'Count'], $outputTable); if ($uncountableTransports) { - $io->note(sprintf('Unable to get message count for the following transports: "%s".', implode('", "', $uncountableTransports))); + $io->note(\sprintf('Unable to get message count for the following transports: "%s".', implode('", "', $uncountableTransports))); } return 0; diff --git a/DependencyInjection/MessengerPass.php b/DependencyInjection/MessengerPass.php index 98ad2058..336b513a 100644 --- a/DependencyInjection/MessengerPass.php +++ b/DependencyInjection/MessengerPass.php @@ -67,14 +67,14 @@ private function registerHandlers(ContainerBuilder $container, array $busIds): v foreach ($container->findTaggedServiceIds('messenger.message_handler', true) as $serviceId => $tags) { foreach ($tags as $tag) { if (isset($tag['bus']) && !\in_array($tag['bus'], $busIds, true)) { - throw new RuntimeException(sprintf('Invalid handler service "%s": bus "%s" specified on the tag "messenger.message_handler" does not exist (known ones are: "%s").', $serviceId, $tag['bus'], implode('", "', $busIds))); + throw new RuntimeException(\sprintf('Invalid handler service "%s": bus "%s" specified on the tag "messenger.message_handler" does not exist (known ones are: "%s").', $serviceId, $tag['bus'], implode('", "', $busIds))); } $className = $this->getServiceClass($container, $serviceId); $r = $container->getReflectionClass($className); if (null === $r) { - throw new RuntimeException(sprintf('Invalid service "%s": class "%s" does not exist.', $serviceId, $className)); + throw new RuntimeException(\sprintf('Invalid service "%s": class "%s" does not exist.', $serviceId, $className)); } if (isset($tag['handles'])) { @@ -94,7 +94,7 @@ private function registerHandlers(ContainerBuilder $container, array $busIds): v $message = $options; $options = []; } else { - 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)); + 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)); } } @@ -112,9 +112,9 @@ private function registerHandlers(ContainerBuilder $container, array $busIds): v if (!\in_array($options['bus'], $busIds)) { // @deprecated since Symfony 6.2, in 7.0 change to: // $messageLocation = isset($tag['handles']) ? 'declared in your tag attribute "handles"' : sprintf('used as argument type in method "%s::%s()"', $r->getName(), $method); - $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)); + $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)); - throw new RuntimeException(sprintf('Invalid configuration '.$messageLocation.' for message "%s": bus "%s" does not exist.', $message, $options['bus'])); + throw new RuntimeException(\sprintf('Invalid configuration '.$messageLocation.' for message "%s": bus "%s" does not exist.', $message, $options['bus'])); } $buses = [$options['bus']]; @@ -123,13 +123,13 @@ private function registerHandlers(ContainerBuilder $container, array $busIds): v if ('*' !== $message && !class_exists($message) && !interface_exists($message, false)) { // @deprecated since Symfony 6.2, in 7.0 change to: // $messageLocation = isset($tag['handles']) ? 'declared in your tag attribute "handles"' : sprintf('used as argument type in method "%s::%s()"', $r->getName(), $method); - $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)); + $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)); - throw new RuntimeException(sprintf('Invalid handler service "%s": class or interface "%s" '.$messageLocation.' not found.', $serviceId, $message)); + throw new RuntimeException(\sprintf('Invalid handler service "%s": class or interface "%s" '.$messageLocation.' not found.', $serviceId, $message)); } if (!$r->hasMethod($method)) { - throw new RuntimeException(sprintf('Invalid handler service "%s": method "%s::%s()" does not exist.', $serviceId, $r->getName(), $method)); + throw new RuntimeException(\sprintf('Invalid handler service "%s": method "%s::%s()" does not exist.', $serviceId, $r->getName(), $method)); } if ('__invoke' !== $method || '' !== $fromTransport) { @@ -148,7 +148,7 @@ private function registerHandlers(ContainerBuilder $container, array $busIds): v } if (null === $message) { - throw new RuntimeException(sprintf('Invalid handler service "%s": method "%s::getHandledMessages()" must return one or more messages.', $serviceId, $r->getName())); + throw new RuntimeException(\sprintf('Invalid handler service "%s": method "%s::getHandledMessages()" must return one or more messages.', $serviceId, $r->getName())); } } } @@ -217,11 +217,11 @@ private function guessHandledClasses(\ReflectionClass $handlerClass, string $ser try { $method = $handlerClass->getMethod($methodName); } catch (\ReflectionException) { - throw new RuntimeException(sprintf('Invalid handler service "%s": class "%s" must have an "%s()" method.', $serviceId, $handlerClass->getName(), $methodName)); + throw new RuntimeException(\sprintf('Invalid handler service "%s": class "%s" must have an "%s()" method.', $serviceId, $handlerClass->getName(), $methodName)); } if (0 === $method->getNumberOfRequiredParameters()) { - throw new RuntimeException(sprintf('Invalid handler service "%s": method "%s::%s()" requires at least one argument, first one being the message it handles.', $serviceId, $handlerClass->getName(), $methodName)); + throw new RuntimeException(\sprintf('Invalid handler service "%s": method "%s::%s()" requires at least one argument, first one being the message it handles.', $serviceId, $handlerClass->getName(), $methodName)); } $parameters = $method->getParameters(); @@ -230,7 +230,7 @@ private function guessHandledClasses(\ReflectionClass $handlerClass, string $ser $type = $parameters[0]->getType(); if (!$type) { - throw new RuntimeException(sprintf('Invalid handler service "%s": argument "$%s" of method "%s::%s()" must have a type-hint corresponding to the message class it handles.', $serviceId, $parameters[0]->getName(), $handlerClass->getName(), $methodName)); + throw new RuntimeException(\sprintf('Invalid handler service "%s": argument "$%s" of method "%s::%s()" must have a type-hint corresponding to the message class it handles.', $serviceId, $parameters[0]->getName(), $handlerClass->getName(), $methodName)); } if ($type instanceof \ReflectionUnionType) { @@ -248,11 +248,11 @@ private function guessHandledClasses(\ReflectionClass $handlerClass, string $ser return ('__invoke' === $methodName) ? $types : array_fill_keys($types, $methodName); } - 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(), implode('|', $invalidTypes))); + 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(), implode('|', $invalidTypes))); } if ($type->isBuiltin()) { - throw new RuntimeException(sprintf('Invalid handler service "%s": type-hint of argument "$%s" in method "%s::%s()" must be a class , "%s" given.', $serviceId, $parameters[0]->getName(), $handlerClass->getName(), $methodName, $type instanceof \ReflectionNamedType ? $type->getName() : (string) $type)); + throw new RuntimeException(\sprintf('Invalid handler service "%s": type-hint of argument "$%s" in method "%s::%s()" must be a class , "%s" given.', $serviceId, $parameters[0]->getName(), $handlerClass->getName(), $methodName, $type instanceof \ReflectionNamedType ? $type->getName() : (string) $type)); } return ('__invoke' === $methodName) ? [$type->getName()] : [$type->getName() => $methodName]; @@ -278,7 +278,7 @@ private function registerReceivers(ContainerBuilder $container, array $busIds): foreach ($container->findTaggedServiceIds('messenger.receiver') as $id => $tags) { $receiverClass = $this->getServiceClass($container, $id); if (!is_subclass_of($receiverClass, ReceiverInterface::class)) { - throw new RuntimeException(sprintf('Invalid receiver "%s": class "%s" must implement interface "%s".', $id, $receiverClass, ReceiverInterface::class)); + throw new RuntimeException(\sprintf('Invalid receiver "%s": class "%s" must implement interface "%s".', $id, $receiverClass, ReceiverInterface::class)); } $receiverMapping[$id] = new Reference($id); @@ -290,7 +290,7 @@ private function registerReceivers(ContainerBuilder $container, array $busIds): $failureTransportsMap[$tag['alias']] = $receiverMapping[$id]; } } - if (!isset($tag['is_consumable']) || $tag['is_consumable'] !== false) { + if (!isset($tag['is_consumable']) || false !== $tag['is_consumable']) { $consumableReceiverNames[] = $tag['alias'] ?? $id; } } @@ -374,7 +374,7 @@ private function registerBusMiddleware(ContainerBuilder $container, string $busI } if (!$container->has($messengerMiddlewareId)) { - throw new RuntimeException(sprintf('Invalid middleware: service "%s" not found.', $id)); + throw new RuntimeException(\sprintf('Invalid middleware: service "%s" not found.', $id)); } if ($container->findDefinition($messengerMiddlewareId)->isAbstract()) { @@ -385,7 +385,7 @@ private function registerBusMiddleware(ContainerBuilder $container, string $busI } $container->setDefinition($messengerMiddlewareId, $childDefinition); } elseif ($arguments) { - throw new RuntimeException(sprintf('Invalid middleware factory "%s": a middleware factory must be an abstract definition.', $id)); + throw new RuntimeException(\sprintf('Invalid middleware factory "%s": a middleware factory must be an abstract definition.', $id)); } $middlewareReferences[$messengerMiddlewareId] = new Reference($messengerMiddlewareId); diff --git a/EventListener/SendFailedMessageForRetryListener.php b/EventListener/SendFailedMessageForRetryListener.php index e012a387..e2e1204e 100644 --- a/EventListener/SendFailedMessageForRetryListener.php +++ b/EventListener/SendFailedMessageForRetryListener.php @@ -165,6 +165,6 @@ private function getSenderForTransport(string $alias): SenderInterface return $this->sendersLocator->get($alias); } - throw new RuntimeException(sprintf('Could not find sender "%s" based on the same receiver to send the failed message to for retry.', $alias)); + throw new RuntimeException(\sprintf('Could not find sender "%s" based on the same receiver to send the failed message to for retry.', $alias)); } } diff --git a/Exception/DelayedMessageHandlingException.php b/Exception/DelayedMessageHandlingException.php index ea785bfe..5bbbcc52 100644 --- a/Exception/DelayedMessageHandlingException.php +++ b/Exception/DelayedMessageHandlingException.php @@ -36,9 +36,9 @@ public function __construct(array $exceptions, ?Envelope $envelope = null) )); if (1 === \count($exceptions)) { - $message = sprintf("A delayed message handler threw an exception: \n\n%s", $exceptionMessages); + $message = \sprintf("A delayed message handler threw an exception: \n\n%s", $exceptionMessages); } else { - $message = sprintf("Some delayed message handlers threw an exception: \n\n%s", $exceptionMessages); + $message = \sprintf("Some delayed message handlers threw an exception: \n\n%s", $exceptionMessages); } $this->exceptions = $exceptions; diff --git a/Exception/HandlerFailedException.php b/Exception/HandlerFailedException.php index ed169958..436d6be2 100644 --- a/Exception/HandlerFailedException.php +++ b/Exception/HandlerFailedException.php @@ -26,12 +26,12 @@ public function __construct(Envelope $envelope, array $exceptions) { $firstFailure = current($exceptions); - $message = sprintf('Handling "%s" failed: ', $envelope->getMessage()::class); + $message = \sprintf('Handling "%s" failed: ', $envelope->getMessage()::class); parent::__construct( $message.(1 === \count($exceptions) ? $firstFailure->getMessage() - : sprintf('%d handlers failed. First failure is: %s', \count($exceptions), $firstFailure->getMessage()) + : \sprintf('%d handlers failed. First failure is: %s', \count($exceptions), $firstFailure->getMessage()) ), (int) $firstFailure->getCode(), $firstFailure diff --git a/Exception/ValidationFailedException.php b/Exception/ValidationFailedException.php index 0a8655e5..140a402b 100644 --- a/Exception/ValidationFailedException.php +++ b/Exception/ValidationFailedException.php @@ -30,7 +30,7 @@ public function __construct(object $violatingMessage, ConstraintViolationListInt $this->violations = $violations; $this->envelope = $envelope; - parent::__construct(sprintf('Message of type "%s" failed validation.', $this->violatingMessage::class)); + parent::__construct(\sprintf('Message of type "%s" failed validation.', $this->violatingMessage::class)); } /** diff --git a/HandleTrait.php b/HandleTrait.php index ac86302a..7e509649 100644 --- a/HandleTrait.php +++ b/HandleTrait.php @@ -34,7 +34,7 @@ trait HandleTrait private function handle(object $message): mixed { if (!isset($this->messageBus)) { - throw new LogicException(sprintf('You must provide a "%s" instance in the "%s::$messageBus" property, but that property has not been initialized yet.', MessageBusInterface::class, static::class)); + throw new LogicException(\sprintf('You must provide a "%s" instance in the "%s::$messageBus" property, but that property has not been initialized yet.', MessageBusInterface::class, static::class)); } $envelope = $this->messageBus->dispatch($message); @@ -42,13 +42,13 @@ private function handle(object $message): mixed $handledStamps = $envelope->all(HandledStamp::class); if (!$handledStamps) { - throw new LogicException(sprintf('Message of type "%s" was handled zero times. Exactly one handler is expected when using "%s::%s()".', get_debug_type($envelope->getMessage()), static::class, __FUNCTION__)); + throw new LogicException(\sprintf('Message of type "%s" was handled zero times. Exactly one handler is expected when using "%s::%s()".', get_debug_type($envelope->getMessage()), static::class, __FUNCTION__)); } if (\count($handledStamps) > 1) { - $handlers = implode(', ', array_map(fn (HandledStamp $stamp): string => sprintf('"%s"', $stamp->getHandlerName()), $handledStamps)); + $handlers = implode(', ', array_map(fn (HandledStamp $stamp): string => \sprintf('"%s"', $stamp->getHandlerName()), $handledStamps)); - throw new LogicException(sprintf('Message of type "%s" was handled multiple times. Only one handler is expected when using "%s::%s()", got %d: %s.', get_debug_type($envelope->getMessage()), static::class, __FUNCTION__, \count($handledStamps), $handlers)); + throw new LogicException(\sprintf('Message of type "%s" was handled multiple times. Only one handler is expected when using "%s::%s()", got %d: %s.', get_debug_type($envelope->getMessage()), static::class, __FUNCTION__, \count($handledStamps), $handlers)); } return $handledStamps[0]->getResult(); diff --git a/Handler/Acknowledger.php b/Handler/Acknowledger.php index 3fa7a8fc..9c5350d7 100644 --- a/Handler/Acknowledger.php +++ b/Handler/Acknowledger.php @@ -63,14 +63,14 @@ public function isAcknowledged(): bool public function __destruct() { if (null !== $this->ack) { - throw new LogicException(sprintf('The acknowledger was not called by the "%s" batch handler.', $this->handlerClass)); + throw new LogicException(\sprintf('The acknowledger was not called by the "%s" batch handler.', $this->handlerClass)); } } private function doAck(?\Throwable $e = null, mixed $result = null): void { if (!$ack = $this->ack) { - throw new LogicException(sprintf('The acknowledger cannot be called twice by the "%s" batch handler.', $this->handlerClass)); + throw new LogicException(\sprintf('The acknowledger cannot be called twice by the "%s" batch handler.', $this->handlerClass)); } $this->ack = null; $this->error = $e; diff --git a/Message/RedispatchMessage.php b/Message/RedispatchMessage.php index c9bcbfa4..e7488305 100644 --- a/Message/RedispatchMessage.php +++ b/Message/RedispatchMessage.php @@ -29,6 +29,6 @@ public function __toString(): string { $message = $this->envelope instanceof Envelope ? $this->envelope->getMessage() : $this->envelope; - return sprintf('%s via %s', $message instanceof \Stringable ? (string) $message : $message::class, implode(', ', (array) $this->transportNames)); + return \sprintf('%s via %s', $message instanceof \Stringable ? (string) $message : $message::class, implode(', ', (array) $this->transportNames)); } } diff --git a/Middleware/HandleMessageMiddleware.php b/Middleware/HandleMessageMiddleware.php index f8e6f317..aa5ddab2 100644 --- a/Middleware/HandleMessageMiddleware.php +++ b/Middleware/HandleMessageMiddleware.php @@ -77,7 +77,7 @@ public function handle(Envelope $envelope, StackInterface $stack): Envelope $result = $this->callHandler($handler, $message, $ack, $envelope->last(HandlerArgumentsStamp::class)); if (!\is_int($result) || 0 > $result) { - throw new LogicException(sprintf('A handler implementing BatchHandlerInterface must return the size of the current batch as a positive integer, "%s" returned from "%s".', \is_int($result) ? $result : get_debug_type($result), get_debug_type($batchHandler))); + throw new LogicException(\sprintf('A handler implementing BatchHandlerInterface must return the size of the current batch as a positive integer, "%s" returned from "%s".', \is_int($result) ? $result : get_debug_type($result), get_debug_type($batchHandler))); } if (!$ack->isAcknowledged()) { @@ -114,7 +114,7 @@ public function handle(Envelope $envelope, StackInterface $stack): Envelope if (null === $handler && !$alreadyHandled) { if (!$this->allowNoHandlers) { - throw new NoHandlerForMessageException(sprintf('No handler for message "%s".', $context['class'])); + throw new NoHandlerForMessageException(\sprintf('No handler for message "%s".', $context['class'])); } $this->logger?->info('No handler for message {class}', $context); diff --git a/Middleware/SendMessageMiddleware.php b/Middleware/SendMessageMiddleware.php index 09571eaf..5564458d 100644 --- a/Middleware/SendMessageMiddleware.php +++ b/Middleware/SendMessageMiddleware.php @@ -63,7 +63,7 @@ public function handle(Envelope $envelope, StackInterface $stack): Envelope } if (!$this->allowNoSenders && !$sender) { - throw new NoSenderForMessageException(sprintf('No sender for message "%s".', $context['class'])); + throw new NoSenderForMessageException(\sprintf('No sender for message "%s".', $context['class'])); } } diff --git a/Middleware/TraceableMiddleware.php b/Middleware/TraceableMiddleware.php index dd1e9976..83a18be0 100644 --- a/Middleware/TraceableMiddleware.php +++ b/Middleware/TraceableMiddleware.php @@ -72,9 +72,9 @@ public function next(): MiddlewareInterface if ($this->stack === $nextMiddleware = $this->stack->next()) { $this->currentEvent = 'Tail'; } else { - $this->currentEvent = sprintf('"%s"', get_debug_type($nextMiddleware)); + $this->currentEvent = \sprintf('"%s"', get_debug_type($nextMiddleware)); } - $this->currentEvent .= sprintf(' on "%s"', $this->busName); + $this->currentEvent .= \sprintf(' on "%s"', $this->busName); $this->stopwatch->start($this->currentEvent, $this->eventCategory); diff --git a/Retry/MultiplierRetryStrategy.php b/Retry/MultiplierRetryStrategy.php index 16bc3b93..b5eaa2f4 100644 --- a/Retry/MultiplierRetryStrategy.php +++ b/Retry/MultiplierRetryStrategy.php @@ -48,17 +48,17 @@ public function __construct(int $maxRetries = 3, int $delayMilliseconds = 1000, $this->maxRetries = $maxRetries; if ($delayMilliseconds < 0) { - throw new InvalidArgumentException(sprintf('Delay must be greater than or equal to zero: "%s" given.', $delayMilliseconds)); + throw new InvalidArgumentException(\sprintf('Delay must be greater than or equal to zero: "%s" given.', $delayMilliseconds)); } $this->delayMilliseconds = $delayMilliseconds; if ($multiplier < 1) { - throw new InvalidArgumentException(sprintf('Multiplier must be greater than zero: "%s" given.', $multiplier)); + throw new InvalidArgumentException(\sprintf('Multiplier must be greater than zero: "%s" given.', $multiplier)); } $this->multiplier = $multiplier; if ($maxDelayMilliseconds < 0) { - throw new InvalidArgumentException(sprintf('Max delay must be greater than or equal to zero: "%s" given.', $maxDelayMilliseconds)); + throw new InvalidArgumentException(\sprintf('Max delay must be greater than or equal to zero: "%s" given.', $maxDelayMilliseconds)); } $this->maxDelayMilliseconds = $maxDelayMilliseconds; } diff --git a/RoutableMessageBus.php b/RoutableMessageBus.php index a33be185..760de866 100644 --- a/RoutableMessageBus.php +++ b/RoutableMessageBus.php @@ -60,7 +60,7 @@ public function dispatch(object $envelope, array $stamps = []): Envelope public function getMessageBus(string $busName): MessageBusInterface { if (!$this->busLocator->has($busName)) { - throw new InvalidArgumentException(sprintf('Bus named "%s" does not exist.', $busName)); + throw new InvalidArgumentException(\sprintf('Bus named "%s" does not exist.', $busName)); } return $this->busLocator->get($busName); diff --git a/Tests/Command/ConsumeMessagesCommandTest.php b/Tests/Command/ConsumeMessagesCommandTest.php index 1a42005c..d9739b4e 100644 --- a/Tests/Command/ConsumeMessagesCommandTest.php +++ b/Tests/Command/ConsumeMessagesCommandTest.php @@ -233,7 +233,7 @@ public function testRunWithMemoryLimit() $busLocator->method('has')->with('dummy-bus')->willReturn(true); $busLocator->method('get')->with('dummy-bus')->willReturn($bus); - $logger = new class() implements LoggerInterface { + $logger = new class implements LoggerInterface { use LoggerTrait; public array $logs = []; diff --git a/Tests/DependencyInjection/MessengerPassTest.php b/Tests/DependencyInjection/MessengerPassTest.php index e75117e5..376462eb 100644 --- a/Tests/DependencyInjection/MessengerPassTest.php +++ b/Tests/DependencyInjection/MessengerPassTest.php @@ -160,7 +160,7 @@ public function testTaggedMessageHandler() unset($tagAttributes['fromTransport']); if ($reflector instanceof \ReflectionMethod) { if (isset($tagAttributes['method'])) { - throw new LogicException(sprintf('AsMessageHandler attribute cannot declare a method on "%s::%s()".', $reflector->class, $reflector->name)); + throw new LogicException(\sprintf('AsMessageHandler attribute cannot declare a method on "%s::%s()".', $reflector->class, $reflector->name)); } $tagAttributes['method'] = $reflector->getName(); } @@ -213,7 +213,7 @@ public function testTaggedMessageHandlerWithUnionTypes() unset($tagAttributes['fromTransport']); if ($reflector instanceof \ReflectionMethod) { if (isset($tagAttributes['method'])) { - throw new LogicException(sprintf('AsMessageHandler attribute cannot declare a method on "%s::%s()".', $reflector->class, $reflector->name)); + throw new LogicException(\sprintf('AsMessageHandler attribute cannot declare a method on "%s::%s()".', $reflector->class, $reflector->name)); } $tagAttributes['method'] = $reflector->getName(); } @@ -734,7 +734,7 @@ public function testUnionTypeArgumentsTypeHandler() public function testUnionBuiltinArgumentTypeHandler() { $this->expectException(RuntimeException::class); - $this->expectExceptionMessage(sprintf('Invalid handler service "%s": type-hint of argument "$message" in method "%s::__invoke()" must be a class , "string|int" given.', UnionBuiltinTypeArgumentHandler::class, UnionBuiltinTypeArgumentHandler::class)); + $this->expectExceptionMessage(\sprintf('Invalid handler service "%s": type-hint of argument "$message" in method "%s::__invoke()" must be a class , "string|int" given.', UnionBuiltinTypeArgumentHandler::class, UnionBuiltinTypeArgumentHandler::class)); $container = $this->getContainerBuilder(); $container ->register(UnionBuiltinTypeArgumentHandler::class, UnionBuiltinTypeArgumentHandler::class) diff --git a/Tests/EventListener/StopWorkerOnCustomStopExceptionListenerTest.php b/Tests/EventListener/StopWorkerOnCustomStopExceptionListenerTest.php index c9e6c6d5..bc335c25 100644 --- a/Tests/EventListener/StopWorkerOnCustomStopExceptionListenerTest.php +++ b/Tests/EventListener/StopWorkerOnCustomStopExceptionListenerTest.php @@ -28,7 +28,7 @@ public static function provideTests(): \Generator yield 'it should not stop (1)' => [new \Exception(), false]; yield 'it should not stop (2)' => [new HandlerFailedException(new Envelope(new \stdClass()), [new \Exception()]), false]; - $t = new class() extends \Exception implements StopWorkerExceptionInterface {}; + $t = new class extends \Exception implements StopWorkerExceptionInterface {}; yield 'it should stop with custom exception' => [$t, true]; yield 'it should stop with core exception' => [new StopWorkerException(), true]; diff --git a/Tests/Exception/HandlerFailedExceptionTest.php b/Tests/Exception/HandlerFailedExceptionTest.php index 177ef663..d38ef9d9 100644 --- a/Tests/Exception/HandlerFailedExceptionTest.php +++ b/Tests/Exception/HandlerFailedExceptionTest.php @@ -23,7 +23,7 @@ class HandlerFailedExceptionTest extends TestCase public function testThatStringErrorCodeConvertsToInteger() { $envelope = new Envelope(new \stdClass()); - $exception = new class() extends \RuntimeException { + $exception = new class extends \RuntimeException { public function __construct() { $this->code = 'HY000'; diff --git a/Tests/Handler/HandleDescriptorTest.php b/Tests/Handler/HandleDescriptorTest.php index 2b802f9e..994c5226 100644 --- a/Tests/Handler/HandleDescriptorTest.php +++ b/Tests/Handler/HandleDescriptorTest.php @@ -39,7 +39,7 @@ public static function provideHandlers(): iterable yield [\Closure::fromCallable(function () {}), 'Closure']; yield [\Closure::fromCallable(new DummyCommandHandler()), DummyCommandHandler::class.'::__invoke']; yield [\Closure::bind(\Closure::fromCallable(function () {}), new \stdClass()), 'Closure']; - yield [new class() { + yield [new class { public function __invoke() { } diff --git a/Tests/Middleware/HandleMessageMiddlewareTest.php b/Tests/Middleware/HandleMessageMiddlewareTest.php index 2b31b8c1..86e9d855 100644 --- a/Tests/Middleware/HandleMessageMiddlewareTest.php +++ b/Tests/Middleware/HandleMessageMiddlewareTest.php @@ -51,7 +51,7 @@ public function testItKeysTheHandlerFailedNestedExceptionsByHandlerDescription() { $message = new DummyMessage('Hey'); $envelope = new Envelope($message); - $handler = new class() { + $handler = new class { public function __invoke() { throw new \Exception('failed'); @@ -100,7 +100,7 @@ public function testItAddsHandledStamps(array $handlers, array $expectedStamps, public static function itAddsHandledStampsProvider(): iterable { - $first = new class() extends HandleMessageMiddlewareTestCallable { + $first = new class extends HandleMessageMiddlewareTestCallable { public function __invoke() { return 'first result'; @@ -108,7 +108,7 @@ public function __invoke() }; $firstClass = $first::class; - $second = new class() extends HandleMessageMiddlewareTestCallable { + $second = new class extends HandleMessageMiddlewareTestCallable { public function __invoke() { return null; @@ -116,7 +116,7 @@ public function __invoke() }; $secondClass = $second::class; - $failing = new class() extends HandleMessageMiddlewareTestCallable { + $failing = new class extends HandleMessageMiddlewareTestCallable { public function __invoke() { throw new \Exception('handler failed.'); @@ -199,7 +199,7 @@ public function testAllowNoHandlers() public function testBatchHandler() { - $handler = new class() implements BatchHandlerInterface { + $handler = new class implements BatchHandlerInterface { public array $processedMessages; use BatchHandlerTrait; @@ -255,7 +255,7 @@ private function process(array $jobs): void public function testBatchHandlerNoAck() { - $handler = new class() implements BatchHandlerInterface { + $handler = new class implements BatchHandlerInterface { use BatchHandlerTrait; public function __invoke(DummyMessage $message, ?Acknowledger $ack = null) @@ -290,7 +290,7 @@ private function process(array $jobs): void public function testBatchHandlerNoBatch() { - $handler = new class() implements BatchHandlerInterface { + $handler = new class implements BatchHandlerInterface { public array $processedMessages; use BatchHandlerTrait; diff --git a/Tests/Middleware/TraceableMiddlewareTest.php b/Tests/Middleware/TraceableMiddlewareTest.php index 7af32bbc..d40461c8 100644 --- a/Tests/Middleware/TraceableMiddlewareTest.php +++ b/Tests/Middleware/TraceableMiddlewareTest.php @@ -32,7 +32,7 @@ public function testHandle() $busId = 'command_bus'; $envelope = new Envelope(new DummyMessage('Hello')); - $middleware = new class() implements MiddlewareInterface { + $middleware = new class implements MiddlewareInterface { public int $calls = 0; public function handle(Envelope $envelope, StackInterface $stack): Envelope diff --git a/Tests/Transport/Serialization/SerializerTest.php b/Tests/Transport/Serialization/SerializerTest.php index b18e7081..97d9eb95 100644 --- a/Tests/Transport/Serialization/SerializerTest.php +++ b/Tests/Transport/Serialization/SerializerTest.php @@ -21,7 +21,6 @@ use Symfony\Component\Messenger\Stamp\ValidationStamp; use Symfony\Component\Messenger\Tests\Fixtures\DummyMessage; use Symfony\Component\Messenger\Transport\Serialization\Serializer; -use Symfony\Component\Serializer as SerializerComponent; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\SerializerInterface as SerializerComponentInterface; @@ -78,7 +77,7 @@ public function testUsesTheCustomFormatAndContext() { $message = new DummyMessage('Foo'); - $serializer = $this->createMock(SerializerComponent\SerializerInterface::class); + $serializer = $this->createMock(SerializerComponentInterface::class); $serializer->expects($this->once())->method('serialize')->with($message, 'csv', ['foo' => 'bar', Serializer::MESSENGER_SERIALIZATION_CONTEXT => true])->willReturn('Yay'); $serializer->expects($this->once())->method('deserialize')->with('Yay', DummyMessage::class, 'csv', ['foo' => 'bar', Serializer::MESSENGER_SERIALIZATION_CONTEXT => true])->willReturn($message); diff --git a/Transport/InMemory/InMemoryTransport.php b/Transport/InMemory/InMemoryTransport.php index 4937c4b3..3ebf82e6 100644 --- a/Transport/InMemory/InMemoryTransport.php +++ b/Transport/InMemory/InMemoryTransport.php @@ -102,7 +102,7 @@ public function send(Envelope $envelope): Envelope /** @var DelayStamp|null $delayStamp */ if ($delayStamp = $envelope->last(DelayStamp::class)) { $now = $this->clock?->now() ?? new \DateTimeImmutable(); - $this->availableAt[$id] = $now->modify(sprintf('+%d seconds', $delayStamp->getDelay() / 1000)); + $this->availableAt[$id] = $now->modify(\sprintf('+%d seconds', $delayStamp->getDelay() / 1000)); } return $envelope; diff --git a/Transport/Sender/SendersLocator.php b/Transport/Sender/SendersLocator.php index f8308ada..3cc054e9 100644 --- a/Transport/Sender/SendersLocator.php +++ b/Transport/Sender/SendersLocator.php @@ -69,7 +69,7 @@ public function getSenders(Envelope $envelope): iterable private function getSenderFromAlias(string $senderAlias): iterable { if (!$this->sendersLocator->has($senderAlias)) { - throw new RuntimeException(sprintf('Invalid senders configuration: sender "%s" is not in the senders locator.', $senderAlias)); + throw new RuntimeException(\sprintf('Invalid senders configuration: sender "%s" is not in the senders locator.', $senderAlias)); } yield $senderAlias => $this->sendersLocator->get($senderAlias); diff --git a/Transport/Serialization/PhpSerializer.php b/Transport/Serialization/PhpSerializer.php index 438fc1a1..50186791 100644 --- a/Transport/Serialization/PhpSerializer.php +++ b/Transport/Serialization/PhpSerializer.php @@ -118,6 +118,6 @@ private function safelyUnserialize(string $contents): Envelope */ public static function handleUnserializeCallback(string $class): never { - throw new MessageDecodingFailedException(sprintf('Message class "%s" not found during decoding.', $class)); + throw new MessageDecodingFailedException(\sprintf('Message class "%s" not found during decoding.', $class)); } } diff --git a/Transport/Serialization/Serializer.php b/Transport/Serialization/Serializer.php index b7f8ea9e..d412a5d4 100644 --- a/Transport/Serialization/Serializer.php +++ b/Transport/Serialization/Serializer.php @@ -49,7 +49,7 @@ public function __construct(?SymfonySerializerInterface $serializer = null, stri public static function create(): self { if (!class_exists(SymfonySerializer::class)) { - throw new LogicException(sprintf('The "%s" class requires Symfony\'s Serializer component. Try running "composer require symfony/serializer" or use "%s" instead.', __CLASS__, PhpSerializer::class)); + throw new LogicException(\sprintf('The "%s" class requires Symfony\'s Serializer component. Try running "composer require symfony/serializer" or use "%s" instead.', __CLASS__, PhpSerializer::class)); } $encoders = [new XmlEncoder(), new JsonEncoder()]; From a5fe68d5ba78ccf6070d3758ddf9ba32d548311d Mon Sep 17 00:00:00 2001 From: Fabien Potencier Date: Sat, 12 Jul 2025 11:35:41 +0200 Subject: [PATCH 5/5] Fix @var phpdoc --- Middleware/RouterContextMiddleware.php | 2 +- .../SendFailedMessageToFailureTransportListenerTest.php | 4 ++-- Tests/Middleware/SendMessageMiddlewareTest.php | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Middleware/RouterContextMiddleware.php b/Middleware/RouterContextMiddleware.php index 742ef30b..effad81d 100644 --- a/Middleware/RouterContextMiddleware.php +++ b/Middleware/RouterContextMiddleware.php @@ -58,7 +58,7 @@ public function handle(Envelope $envelope, StackInterface $stack): Envelope $currentPathInfo = $context->getPathInfo(); $currentQueryString = $context->getQueryString(); - /* @var RouterContextStamp $contextStamp */ + /** @var RouterContextStamp $contextStamp */ $context ->setBaseUrl($contextStamp->getBaseUrl()) ->setMethod($contextStamp->getMethod()) diff --git a/Tests/EventListener/SendFailedMessageToFailureTransportListenerTest.php b/Tests/EventListener/SendFailedMessageToFailureTransportListenerTest.php index 9060ff51..a6473e6c 100644 --- a/Tests/EventListener/SendFailedMessageToFailureTransportListenerTest.php +++ b/Tests/EventListener/SendFailedMessageToFailureTransportListenerTest.php @@ -26,7 +26,7 @@ public function testItSendsToTheFailureTransportWithSenderLocator() $receiverName = 'my_receiver'; $sender = $this->createMock(SenderInterface::class); $sender->expects($this->once())->method('send')->with($this->callback(function ($envelope) use ($receiverName) { - /* @var Envelope $envelope */ + /** @var Envelope $envelope */ $this->assertInstanceOf(Envelope::class, $envelope); /** @var SentToFailureTransportStamp $sentToFailureTransportStamp */ @@ -101,7 +101,7 @@ public function testItSendsToTheFailureTransportWithMultipleFailedTransports() $receiverName = 'my_receiver'; $sender = $this->createMock(SenderInterface::class); $sender->expects($this->once())->method('send')->with($this->callback(function ($envelope) use ($receiverName) { - /* @var Envelope $envelope */ + /** @var Envelope $envelope */ $this->assertInstanceOf(Envelope::class, $envelope); /** @var SentToFailureTransportStamp $sentToFailureTransportStamp */ diff --git a/Tests/Middleware/SendMessageMiddlewareTest.php b/Tests/Middleware/SendMessageMiddlewareTest.php index df402764..280e019a 100644 --- a/Tests/Middleware/SendMessageMiddlewareTest.php +++ b/Tests/Middleware/SendMessageMiddlewareTest.php @@ -41,7 +41,7 @@ public function testItSendsTheMessageToAssignedSender() $envelope = $middleware->handle($envelope, $this->getStackMock(false)); - /* @var SentStamp $stamp */ + /** @var SentStamp $stamp */ $this->assertInstanceOf(SentStamp::class, $stamp = $envelope->last(SentStamp::class), 'it adds a sent stamp'); $this->assertSame('my_sender', $stamp->getSenderAlias()); $this->assertStringMatchesFormat('Mock_SenderInterface_%s', $stamp->getSenderClass());