72 lines
2.1 KiB
PHP
72 lines
2.1 KiB
PHP
<?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};
|
|
}
|
|
}
|