71 lines
1.9 KiB
PHP
71 lines
1.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Infrastructure\Adapters\Repositories;
|
|
|
|
use Domain\Models\Entities\Basket;
|
|
use Domain\Models\ValueObjects\Entities\BasketId;
|
|
use Domain\Ports\Repositories\BasketRepository;
|
|
use Illuminate\Contracts\Session\Session;
|
|
use Infrastructure\Adapters\Serializers\BasketSerializer;
|
|
|
|
class SessionBasketRepository implements BasketRepository
|
|
{
|
|
public function __construct(
|
|
private readonly Session $session,
|
|
private readonly string $sessionKeyPrefix,
|
|
private readonly BasketSerializer $serializer
|
|
) {
|
|
}
|
|
|
|
private function getSessionKey(BasketId $id): string
|
|
{
|
|
return $this->sessionKeyPrefix . $id->value;
|
|
}
|
|
|
|
#[\Override]
|
|
public function find(BasketId $id): ?Basket
|
|
{
|
|
$sessionKey = $this->getSessionKey($id);
|
|
|
|
if ($this->session->has($sessionKey)) {
|
|
$sessionData = $this->session->get($sessionKey);
|
|
|
|
if (is_string($sessionData)) {
|
|
try {
|
|
/** @var array<string, mixed> $decoded */
|
|
$decoded = json_decode(
|
|
$sessionData,
|
|
true,
|
|
512,
|
|
JSON_THROW_ON_ERROR
|
|
);
|
|
|
|
if (is_array($decoded)) {
|
|
return $this->serializer->fromArray($decoded);
|
|
}
|
|
} catch (\Throwable $e) {
|
|
// Ignore and fall back to null
|
|
}
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
#[\Override]
|
|
public function persist(Basket $basket): void
|
|
{
|
|
$this->session->put(
|
|
$this->getSessionKey($basket->id),
|
|
json_encode($this->serializer->toArray($basket), JSON_THROW_ON_ERROR)
|
|
);
|
|
}
|
|
|
|
#[\Override]
|
|
public function delete(Basket $basket): void
|
|
{
|
|
$this->session->forget($this->getSessionKey($basket->id));
|
|
}
|
|
}
|