Files
emails/cli/common/Command/Messages.php
2023-06-08 20:49:27 -04:00

68 lines
2.1 KiB
PHP

<?php
namespace ProVM\Common\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use ProVM\Common\Service\Communicator;
use function Safe\json_decode;
#[AsCommand(
name: 'messages:grab',
description: 'Run grab messages job for registered mailboxes',
aliases: ['messages'],
hidden: false
)]
class Messages extends Command
{
public function __construct(Communicator $communicator, string $name = null)
{
$this->setCommunicator($communicator);
parent::__construct($name);
}
protected Communicator $communicator;
public function getCommunicator(): Communicator
{
return $this->communicator;
}
public function setCommunicator(Communicator $communicator): Messages
{
$this->communicator = $communicator;
return $this;
}
protected function getMailboxes(): array
{
$response = $this->getCommunicator()->get('/mailboxes/registered');
return json_decode($response->getBody()->getContents())->mailboxes;
}
protected function grabMessages(string $mailbox): int
{
$response = $this->getCommunicator()->put('/messages/grab', ['mailboxes' => [$mailbox]]);
$body = json_decode($response->getBody()->getContents());
return $body->message_count;
}
public function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$io->title('Messages');
$io->section('Grabbing Registered Mailboxes');
$mailboxes = $this->getMailboxes();
$io->text('Found ' . count($mailboxes) . ' registered mailboxes.');
$io->section('Grabbing Messages');
foreach ($mailboxes as $mailbox) {
$message_count = $this->grabMessages($mailbox->name);
$io->text("Found {$message_count} messages in {$mailbox->name}.");
}
$io->success('Done.');
return Command::SUCCESS;
}
}