ldc-cocotte/domain/Services/BasketService.php

90 lines
2.3 KiB
PHP

<?php
declare(strict_types=1);
namespace Domain\Services;
use Domain\Events\BasketHasBeenModified;
use Domain\Events\BasketRemoved;
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;
use Shared\DDD\DomainEventDispatcher;
class BasketService
{
public function __construct(
private readonly BasketRepository $repository,
private readonly ProductRepository $productRepository,
private readonly SessionService $sessionService,
private readonly DomainEventDispatcher $eventDispatcher,
) {
}
public function getBasket(): Basket
{
$basketId = $this->getBasketId();
return $this->repository->find($basketId) ?? new Basket($basketId, []);
}
public function hasItems(): bool
{
return $this->getBasket()->countItems() > 0;
}
public function add(ProductId $productId, int $qty = 1): void
{
$basketProduct = $this->productRepository->getBasketProduct($productId, $qty);
$basket = $this->getBasket();
$basket->addOrUpdate($basketProduct);
$this->persistBasket($basket);
}
public function remove(ProductId $productId, int $qty = 1): void
{
$basket = $this->getBasket();
$basket->remove($productId, $qty);
$this->persistBasket($basket);
}
public function removeLine(ProductId $productId): void
{
$basket = $this->getBasket();
$basket->removeLine($productId);
$this->persistBasket($basket);
}
public function empty(): void
{
$basket = $this->getBasket();
$this->deleteBasket($basket);
}
private function persistBasket(Basket $basket): void
{
$this->repository->persist($basket);
$this->eventDispatcher->dispatch(new BasketHasBeenModified($basket->id));
}
private function deleteBasket(Basket $basket): void
{
$this->repository->delete($basket);
$this->eventDispatcher->dispatch(new BasketRemoved($basket->id));
}
private function getBasketId(): BasketId
{
$sessionId = $this->sessionService->get();
return new BasketId($sessionId->value);
}
}