<?php
namespace App\EventSubscriber\Shop\OrderSave;
use App\Entity\Shop\DeliveryMethod;
use App\Entity\Shop\PaymentMethod;
use App\Event\Shop\OrderSaveEvent;
use App\Exception\Shop\OrderValidationException;
use App\Shop\ShopManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* @author Przemysław Chrupek <przemyslaw.chrupek@avt.pl>
*/
class BasicOrderValidationSubscriber implements EventSubscriberInterface
{
protected ShopManager $shopManager;
public function __construct(ShopManager $shopManager)
{
$this->shopManager = $shopManager;
}
public static function getSubscribedEvents()
{
return [
OrderSaveEvent::NAME => [
['shopEnabled', 1000],
['isEmpty', 999],
['isSellable', 998],
['isEnoughQuantity', 997],
['isDeliveryMethodSelected', 996],
['isPaymentMethodSelected', 995],
]
];
}
public function shopEnabled(OrderSaveEvent $event): void
{
if (!$this->shopManager->shopEnabled())
throw new OrderValidationException('Nie można utworzyć zamówienia');
}
public function isEmpty(OrderSaveEvent $event): void
{
if ($event->getOrder()->getProducts()->isEmpty())
throw new OrderValidationException('Zamówienie musi zawierać przynajmniej jeden produkt');
}
public function isSellable(OrderSaveEvent $event): void
{
foreach ($event->getOrder()->getProducts() as $product) {
if ($product->getProduct() == null ||
(!$this->shopManager->isProduct($product->getProduct()->getContent()) &&
!$this->shopManager->isAddition($product->getProduct()->getContent()))
)
throw new OrderValidationException(sprintf('Produkt "%s" nie jest już dostępny', $product->getName()));
}
}
public function isEnoughQuantity(OrderSaveEvent $event): void
{
foreach ($event->getOrder()->getProducts() as $product) {
$baseProduct = $product->getProduct();
if ($baseProduct->getQuantity() !== null) { // Check if quantity for product is set
if ($baseProduct->getQuantity() < $product->getQuantity())
throw new OrderValidationException(sprintf('Niewystarczająca ilość produktu "%s" w magazynie', $product->getName()));
}
}
}
public function isDeliveryMethodSelected(OrderSaveEvent $event): void
{
if (!$event->getOrder()->getDeliveryMethod() instanceof DeliveryMethod)
throw new OrderValidationException('Proszę wybrać metodę dostawy');
}
public function isPaymentMethodSelected(OrderSaveEvent $event): void
{
if (!$event->getOrder()->getPaymentMethod() instanceof PaymentMethod)
throw new OrderValidationException('Proszę wybrać metodę płatności');
}
}