Files
kupshop/bundles/KupShop/PreordersBundle/Util/UserPreorderMessages.php
2025-08-02 16:30:27 +02:00

58 lines
1.4 KiB
PHP

<?php
declare(strict_types=1);
namespace KupShop\PreordersBundle\Util;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\DBAL\Driver\Exception;
use KupShop\PreordersBundle\Entity\UserPreorder;
use KupShop\PreordersBundle\Entity\UserPreorderMessage;
/**
* @extends ArrayCollection<int, UserPreorderMessage>
*/
class UserPreorderMessages extends ArrayCollection implements \JsonSerializable, PersistentCollection
{
public function __construct(
private readonly UserPreorder $userPreorder,
) {
$messages = $this->fetchMessages();
parent::__construct(array_map(
fn (array $m) => UserPreorderMessage::createFromArray($m),
$messages,
));
}
public function save(): ?\Throwable
{
$messages = $this->toArray();
usort($messages, fn (UserPreorderMessage $m0, UserPreorderMessage $m1) => $m0->date <=> $m1->date);
try {
UserPreordersDataUtil::upsert($this->userPreorder, messages: $messages);
} catch (\Doctrine\DBAL\Exception $e) {
return $e;
}
return null;
}
private function fetchMessages(): array
{
try {
$data = UserPreordersDataUtil::get($this->userPreorder);
} catch (\Doctrine\DBAL\Exception|Exception) {
return [];
}
return $data['history'] ?? [];
}
public function jsonSerialize(): mixed
{
return $this->toArray();
}
}