Jobs setup
This commit is contained in:
71
cli/common/Service/Jobs.php
Normal file
71
cli/common/Service/Jobs.php
Normal file
@ -0,0 +1,71 @@
|
||||
<?php
|
||||
namespace ProVM\Service;
|
||||
|
||||
use Psr\Log\LoggerInterface;
|
||||
use ProVM\Exception\Response\{EmptyResponse, MissingResponse};
|
||||
use function Safe\json_decode;
|
||||
|
||||
class Jobs
|
||||
{
|
||||
public function __construct(protected Communicator $communicator, protected LoggerInterface $logger) {}
|
||||
|
||||
public function getPending(): array
|
||||
{
|
||||
$this->logger->info('Getting pending jobs');
|
||||
$response = $this->communicator->get('/jobs/pending');
|
||||
$body = $response->getBody()->getContents();
|
||||
if (trim($body) === '') {
|
||||
return [];
|
||||
}
|
||||
$json = json_decode($body);
|
||||
if (!isset($json->jobs)) {
|
||||
return [];
|
||||
}
|
||||
return $json->jobs;
|
||||
}
|
||||
public function get(int $job_id): object
|
||||
{
|
||||
$this->logger->info("Getting Job {$job_id}");
|
||||
$uri = "/job/{$job_id}";
|
||||
return $this->send($uri, 'job');
|
||||
}
|
||||
public function run(object $job): bool
|
||||
{
|
||||
$this->logger->debug("Running Job {$job->id}");
|
||||
$base_command = '/app/bin/emails';
|
||||
$cmd = [$base_command, $job->command];
|
||||
if ($job->arguments !== '') {
|
||||
$cmd []= $job->arguments;
|
||||
}
|
||||
$cmd = implode(' ', $cmd);
|
||||
$response = shell_exec($cmd);
|
||||
if ($response !== false) {
|
||||
return $this->finished($job->id);
|
||||
}
|
||||
return $this->failure($job->id);
|
||||
}
|
||||
|
||||
protected function finished(int $job_id): bool
|
||||
{
|
||||
$uri = "/job/{$job_id}/finish";
|
||||
return $this->send($uri, 'status');
|
||||
}
|
||||
protected function failure(int $job_id): bool
|
||||
{
|
||||
$uri = "/job/{$job_id}/failed";
|
||||
return $this->send($uri, 'status');
|
||||
}
|
||||
protected function send(string $uri, string $param): mixed
|
||||
{
|
||||
$response = $this->communicator->get($uri);
|
||||
$body = $response->getBody()->getContents();
|
||||
if (trim($body) === '') {
|
||||
throw new EmptyResponse($uri);
|
||||
}
|
||||
$json = json_decode($body);
|
||||
if (!isset($json->{$param})) {
|
||||
throw new MissingResponse($param);
|
||||
}
|
||||
return $json->{$param};
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user