Files
oficial/cli/src/Command/Queue.php
2025-05-16 13:56:32 -04:00

64 lines
2.1 KiB
PHP

<?php
namespace Incoviba\Command;
use DateTimeImmutable;
use Psr\Http\Client\ClientInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console;
use Incoviba\Service\Job;
use Incoviba\Common\Alias\Command;
#[Console\Attribute\AsCommand(
name: 'queue',
description: 'Run queue'
)]
class Queue extends Command
{
public function __construct(ClientInterface $client, LoggerInterface $logger,
protected Job $jobService, ?string $name = null)
{
parent::__construct($client, $logger, $name);
}
public function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output): int
{
$this->logger->debug("Running {$this->getName()}");
$io = new Console\Style\SymfonyStyle($input, $output);
$now = new DateTimeImmutable();
$io->title("[{$now->format('Y-m-d H:i:s e')}] Running Queue...");
$jobs = $this->getJobs($output);
if (count($jobs) === 0) {
return Console\Command\Command::SUCCESS;
}
return $this->runJobs($output, $jobs);
}
protected function getJobs(Console\Output\OutputInterface $output): array
{
$this->logger->debug("Getting jobs");
$jobs = $this->jobService->getPending();
return array_column($jobs, 'id');
}
protected function runJobs(Console\Output\OutputInterface $output, array $jobs): int
{
$errors = 0;
foreach ($jobs as $job) {
if ($this->runJob($output, $job) === Console\Command\Command::FAILURE) {
$errors ++;
}
}
return $errors === 0 ? Console\Command\Command::SUCCESS : Console\Command\Command::FAILURE;
}
protected function runJob(Console\Output\OutputInterface $output, int $job_id): int
{
$uri = "/api/queue/run/{$job_id}";
$output->writeln("GET {$uri}");
$response = $this->client->get($uri);
$output->writeln("Response Code: {$response->getStatusCode()}");
return ((int) floor($response->getStatusCode() / 100) === 2) ? Console\Command\Command::SUCCESS : Console\Command\Command::FAILURE;
}
}