Files
emails/api/src/Model/Job.php
2023-06-12 21:14:07 -04:00

107 lines
2.5 KiB
PHP

<?php
namespace ProVM\Emails\Model;
use DateTimeInterface;
use ProVM\Common\Define\Model;
use ProVM\Common\Exception\Database\BlankResult;
use ProVM\Common\Exception\Job\Stateless;
use ProVM\Emails;
class Job implements Model
{
protected int $id;
protected string $command;
protected string $arguments;
public function getId(): int
{
return $this->id;
}
public function getCommand(): string
{
return $this->command;
}
public function getArguments(): string
{
return $this->arguments ?? '';
}
public function setId(int $id): Job
{
$this->id = $id;
return $this;
}
public function setCommand(string $command): Job
{
$this->command = $command;
return $this;
}
public function setArguments(string $arguments): Job
{
$this->arguments = $arguments;
return $this;
}
protected Emails\Repository\State\Job $stateRepository;
public function getStateRepository(): Emails\Repository\State\Job
{
return $this->stateRepository;
}
public function setStateRepository(Emails\Repository\State\Job $repository): Job
{
$this->stateRepository = $repository;
return $this;
}
protected array $states;
public function getStates(): array
{
if (!isset($this->states)) {
try {
$this->setStates($this->getStateRepository()->fetchByJob($this->getId()));
} catch (BlankResult $e) {
return [];
}
}
return $this->states;
}
public function addState(State\Job $state): Job
{
$this->states []= $state;
return $this;
}
public function setStates(array $states): Job
{
foreach ($states as $state) {
$this->addState($state);
}
return $this;
}
public function isExecuted(): bool
{
return $this->lastState()->getStatus() === State\Job::Executed;
}
public function lastState(): State\Job
{
if (count($this->getStates()) === 0) {
throw new Stateless($this->getId());
}
return $this->getStates()[array_key_last($this->getStates())];
}
public function toArray(): array
{
return [
'id' => $this->getId(),
'command' => $this->getCommand(),
'arguments' => $this->getArguments(),
'states' => $this->getStates()
];
}
public function jsonSerialize(): mixed
{
return $this->toArray();
}
}