Files
emails/api/src/Model/Mailbox.php
2022-11-29 08:57:56 -03:00

122 lines
3.0 KiB
PHP

<?php
namespace ProVM\Emails\Model;
use DateTimeInterface;
use ProVM\Common\Define\Model;
use ProVM\Common\Exception\Database\BlankResult;
use ProVM\Common\Exception\EmptyMailbox;
use ProVM\Common\Exception\Mailbox\Stateless;
use Safe\DateTimeImmutable;
class Mailbox implements Model
{
protected int $id;
protected string $name;
protected int $validity;
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getValidity(): int
{
return $this->validity;
}
public function setId(int $id): Mailbox
{
$this->id = $id;
return $this;
}
public function setName(string $name): Mailbox
{
$this->name = $name;
return $this;
}
public function setValidity(int $uidvalidity): Mailbox
{
$this->validity = $uidvalidity;
return $this;
}
protected \ProVM\Emails\Repository\State\Mailbox $stateRepository;
public function getStateRepository(): \ProVM\Emails\Repository\State\Mailbox
{
return $this->stateRepository;
}
public function setStateRepository(\ProVM\Emails\Repository\State\Mailbox $repository): Mailbox
{
$this->stateRepository = $repository;
return $this;
}
protected array $states;
public function getStates(): array
{
if (!isset($this->states)) {
try {
$this->setStates($this->getStateRepository()->fetchByMailbox($this->getId()));
} catch (BlankResult $e) {
return [];
}
}
return $this->states;
}
public function addState(\ProVM\Emails\Model\State\Mailbox $state): Mailbox
{
$this->states []= $state;
return $this;
}
public function setStates(array $states): Mailbox
{
foreach ($states as $state) {
$this->addState($state);
}
return $this;
}
public function lastState(): State\Mailbox
{
if (count($this->getStates()) === 0) {
throw new Stateless($this);
}
return $this->getStates()[array_key_last($this->getStates())];
}
public function lastChecked(): ?DateTimeInterface
{
if (count($this->getStates()) == 0) {
return null;
}
return $this->lastState()->getDateTime();
}
public function lastCount(): int
{
if (count($this->getStates()) == 0) {
return 0;
}
return $this->lastState()->getCount();
}
public function lastPosition(): int
{
$state = $this->lastState()->getUIDs();
return array_key_last($state);
}
public function toArray(): array
{
return [
'id' => $this->getId(),
'name' => $this->getName(),
//'validity' => $this->getValidity(),
'last_checked' => [
'date' => $this->lastChecked() ?? 'never',
'count' => $this->lastCount() ?? 0
]
];
}
}