Files
oficial/app/src/Service/Queue.php

81 lines
2.3 KiB
PHP
Raw Normal View History

2025-05-10 12:30:35 -04:00
<?php
namespace Incoviba\Service;
use Exception;
2025-05-13 20:18:40 -04:00
use Psr\Http\Message\RequestInterface;
2025-05-10 12:30:35 -04:00
use Psr\Log\LoggerInterface;
use Incoviba\Common\Ideal;
use Incoviba\Exception\ServiceAction\{Create, Read};
use Incoviba\Service;
class Queue extends Ideal\Service
{
public function __construct(LoggerInterface $logger, protected Service\Job $jobService, Worker $defaultWorker)
{
parent::__construct($logger);
$this->register('default', $defaultWorker);
}
protected array $workers;
public function register(string $name, Worker $worker): self
{
$this->workers[strtolower($name)] = $worker;
return $this;
}
public function enqueue(array $configuration): bool
{
try {
$this->jobService->add($configuration);
return true;
} catch (Create $exception) {
$final = new Exception("Could not enqueue job", 0, $exception);
$this->logger->warning($final);
return false;
}
}
2025-05-13 20:18:40 -04:00
public function run(?RequestInterface $request): bool
2025-05-10 12:30:35 -04:00
{
try {
$jobs = $this->jobService->getPending();
} catch (Read $exception) {
$final = new Exception("Could not get pending jobs", 0, $exception);
$this->logger->warning($final);
return false;
}
2025-05-12 19:46:09 -04:00
$errors = [];
2025-05-10 12:30:35 -04:00
foreach ($jobs as $job) {
$type = 'default';
if (isset($job->configuration['type'])) {
$type = strtolower($job->configuration['type']);
}
if (!isset($this->workers[$type])) {
$type = 'default';
}
$worker = $this->workers[$type];
2025-05-13 20:18:40 -04:00
if (is_a($worker, Service\Worker\Request::class)) {
$worker->setRequest($request);
}
2025-05-10 12:30:35 -04:00
try {
2025-05-12 19:46:09 -04:00
if (!$worker->execute($job)) {
$errors []= $job->id;
2025-05-13 20:18:40 -04:00
continue;
}
if (!$this->jobService->execute($job)) {
$errors []= $job->id;
2025-05-12 19:46:09 -04:00
}
2025-05-10 12:30:35 -04:00
} catch (Exception $exception) {
$final = new Exception("Could not run job", 0, $exception);
$this->logger->warning($final);
2025-05-12 19:46:09 -04:00
$errors []= $job->id;
2025-05-10 12:30:35 -04:00
}
2025-05-13 20:18:40 -04:00
break;
2025-05-10 12:30:35 -04:00
}
2025-05-12 19:46:09 -04:00
return count($errors) === 0;
2025-05-10 12:30:35 -04:00
}
}