Files
emails/api/common/Service/Jobs.php
2023-06-12 21:14:07 -04:00

95 lines
2.7 KiB
PHP

<?php
namespace ProVM\Common\Service;
use Illuminate\Support\Facades\Date;
use PDOException;
use ProVM\Common\Exception\Database\BlankResult;
use Safe\DateTimeImmutable;
use ProVM\Emails\Repository;
use ProVM\Emails\Model;
class Jobs extends Base
{
public function __construct(Repository\Job $repository, protected Repository\State\Job $stateRepository)
{
$this->setRepository($repository);
}
protected Repository\Job $repository;
public function getRepository(): Repository\Job
{
return $this->repository;
}
public function setRepository(Repository\Job $repository): Jobs
{
$this->repository = $repository;
return $this;
}
public function queue(string $command, ?array $arguments = null): bool
{
$data = [
'command' => $command,
'arguments' => implode(' ', $arguments)
];
try {
$job = $this->getRepository()->create($data);
$this->getRepository()->save($job);
$data = [
'job_id' => $job->getId(),
'date_time' => (new DateTimeImmutable())->format('Y-m-d H:i:s'),
'status' => Model\State\Job::Pending
];
$state = $this->stateRepository->create($data);
$this->stateRepository->save($state);
return true;
} catch (PDOException $e) {
return false;
}
}
public function getPending(): array
{
return $this->getRepository()->fetchAllPending();
}
public function getPendingByCommand(string $command): array
{
try {
return $this->getRepository()->fetchAllPendingByCommand($command);
} catch (BlankResult $e) {
return [];
}
}
public function finish(int $job_id): bool
{
$data = [
'job_id' => $job_id,
'date_time' => (new DateTimeImmutable())->format('Y-m-d H:i:s'),
'status' => Model\State\Job::Executed
];
try {
$state = $this->stateRepository->create($data);
$this->stateRepository->save($state);
return true;
} catch (PDOException $e) {
return false;
}
}
public function failed(int $job_id): bool
{
$data = [
'job_id' => $job_id,
'date_time' => (new DateTimeImmutable())->format('Y-m-d H:i:s'),
'status' => Model\State\Job::Failure
];
try {
$state = $this->stateRepository->create($data);
$this->stateRepository->save($state);
return true;
} catch (PDOException $e) {
return false;
}
}
}