|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Queue\Swoole\Command; |
| 6 | + |
| 7 | +use Dot\DependencyInjection\Attribute\Inject; |
| 8 | +use Redis; |
| 9 | +use RedisException; |
| 10 | +use Symfony\Component\Console\Attribute\AsCommand; |
| 11 | +use Symfony\Component\Console\Command\Command; |
| 12 | +use Symfony\Component\Console\Input\InputInterface; |
| 13 | +use Symfony\Component\Console\Output\OutputInterface; |
| 14 | + |
| 15 | +use function count; |
| 16 | +use function json_encode; |
| 17 | +use function str_repeat; |
| 18 | + |
| 19 | +use const JSON_PRETTY_PRINT; |
| 20 | +use const JSON_UNESCAPED_UNICODE; |
| 21 | + |
| 22 | +#[AsCommand( |
| 23 | + name: 'inventory', |
| 24 | + description: 'Get all queued messages from Redis stream "messages"', |
| 25 | +)] |
| 26 | +class GetQueuedMessagesCommand extends Command |
| 27 | +{ |
| 28 | + protected static string $defaultName = 'inventory'; |
| 29 | + |
| 30 | + private Redis $redis; |
| 31 | + |
| 32 | + #[Inject('redis')] |
| 33 | + public function __construct(Redis $redis) |
| 34 | + { |
| 35 | + parent::__construct(self::$defaultName); |
| 36 | + $this->redis = $redis; |
| 37 | + } |
| 38 | + |
| 39 | + protected function configure(): void |
| 40 | + { |
| 41 | + $this->setDescription('Get all queued messages from Redis stream "messages"'); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * @throws RedisException |
| 46 | + */ |
| 47 | + protected function execute(InputInterface $input, OutputInterface $output): int |
| 48 | + { |
| 49 | + $entries = $this->redis->xRange('messages', '-', '+'); |
| 50 | + |
| 51 | + if (empty($entries)) { |
| 52 | + $output->writeln('<info>No messages queued found in Redis stream "messages".</info>'); |
| 53 | + return Command::SUCCESS; |
| 54 | + } |
| 55 | + |
| 56 | + foreach ($entries as $id => $entry) { |
| 57 | + $output->writeln("<info>Message ID:</info> $id"); |
| 58 | + $output->writeln(json_encode($entry, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); |
| 59 | + $output->writeln(str_repeat('-', 40)); |
| 60 | + } |
| 61 | + |
| 62 | + $total = count($entries); |
| 63 | + $output->writeln("<info>Total queued messages in stream 'messages':</info> $total"); |
| 64 | + $output->writeln(str_repeat('-', 40)); |
| 65 | + |
| 66 | + return Command::SUCCESS; |
| 67 | + } |
| 68 | +} |
0 commit comments