<?php
namespace App\EventSubscriber\Shop\CartValidation;
use App\Event\Shop\AddProductToCartValidationEvent;
use App\Exception\Shop\AddProductToCartValidationException;
use App\Shop\ShopManager;
use App\Shop\VirtualCart\VirtualCart;
use App\Shop\VirtualCart\VirtualProduct;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* @author Przemysław Chrupek <przemyslaw.chrupek@avt.pl>
*/
class CanSellProductValidationSubscriber implements EventSubscriberInterface
{
protected ShopManager $shopManager;
public function __construct(ShopManager $shopManager)
{
$this->shopManager = $shopManager;
}
public static function getSubscribedEvents()
{
return [
AddProductToCartValidationEvent::NAME => [
['shopEnabled', 1000],
['isSellable', 999],
['isEnoughQuantity', 998],
]
];
}
public function shopEnabled(AddProductToCartValidationEvent $event): void
{
if (!$this->shopManager->shopEnabled())
throw new AddProductToCartValidationException('Produkt nie może zostać dodany do koszyka');
}
public function isSellable(AddProductToCartValidationEvent $event): void
{
if (!$this->shopManager->isProduct($event->getProduct()->getContent()) &&
!$this->shopManager->isAddition($event->getProduct()->getContent())
)
throw new AddProductToCartValidationException('Produkt nie może zostać dodany do koszyka');
}
public function isEnoughQuantity(AddProductToCartValidationEvent $event): void
{
$product = $event->getProduct();
$quantity = $event->getQuantity();
$productExistInCart = $event->getCart()->getProductFromCartByProductId($product->getId());
if ($product->getQuantity() !== null) { // Check if quantity for product is set
if ($product->getQuantity() < $quantity) {
throw new AddProductToCartValidationException('Niewystarczająca ilość produktu w magazynie');
}
if ($productExistInCart instanceof VirtualProduct &&
(($productExistInCart->getQuantity() + $quantity) > $product->getQuantity())
) {
throw new AddProductToCartValidationException('Niewystarczająca ilość produktu w magazynie');
}
}
}
}