81 lines
2.1 KiB
PHP
81 lines
2.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Domain\Services;
|
|
|
|
use Domain\Models\Entities\Basket;
|
|
use Domain\Models\ValueObjects\Entities\BasketId;
|
|
use Domain\Models\ValueObjects\Entities\ProductId;
|
|
use Domain\Ports\Repositories\BasketRepository;
|
|
use Domain\Ports\Repositories\ProductRepository;
|
|
use Domain\Ports\Services\SessionService;
|
|
|
|
class BasketService
|
|
{
|
|
public function __construct(
|
|
private readonly BasketRepository $repository,
|
|
private readonly ProductRepository $productRepository,
|
|
private readonly SessionService $sessionService
|
|
) {
|
|
}
|
|
|
|
public function getBasket(): Basket
|
|
{
|
|
$basketId = $this->getBasketId();
|
|
|
|
return $this->repository->find($basketId) ?? new Basket($basketId, []);
|
|
}
|
|
|
|
public function add(ProductId $productId, int $qty = 1): void
|
|
{
|
|
$basketProduct = $this->productRepository->getBasketProduct($productId, $qty);
|
|
$basket = $this->getBasket();
|
|
|
|
$basket->addOrUpdate($basketProduct);
|
|
|
|
$this->repository->persist($basket);
|
|
}
|
|
|
|
public function remove(ProductId $productId, int $qty = 1): void
|
|
{
|
|
$basket = $this->getBasket();
|
|
$basket->remove($productId, $qty);
|
|
|
|
$this->repository->persist($basket);
|
|
}
|
|
|
|
public function removeLine(ProductId $productId): void
|
|
{
|
|
$basket = $this->getBasket();
|
|
$basket->removeLine($productId);
|
|
|
|
$this->repository->persist($basket);
|
|
}
|
|
|
|
public function revalidateBasket(Basket $basket): Basket
|
|
{
|
|
$refreshedItems = [];
|
|
|
|
foreach ($basket->items() as $item) {
|
|
$refreshedItems[] = $this->productRepository->getBasketProduct($item->id, $item->qty);
|
|
}
|
|
|
|
$refreshedBasket = new Basket($basket->id, $refreshedItems);
|
|
$this->repository->persist($refreshedBasket);
|
|
|
|
return $refreshedBasket;
|
|
}
|
|
|
|
public function empty(): void
|
|
{
|
|
$this->repository->delete($this->getBasket());
|
|
}
|
|
|
|
private function getBasketId(): BasketId
|
|
{
|
|
$sessionId = $this->sessionService->get();
|
|
|
|
return new BasketId($sessionId->value);
|
|
}
|
|
}
|