Files
kupshop/bundles/KupShop/ReservationBundle/EventSubscriber/ReservationSubscriber.php
2025-08-02 16:30:27 +02:00

87 lines
3.1 KiB
PHP

<?php
declare(strict_types=1);
namespace KupShop\ReservationBundle\EventSubscriber;
use KupShop\ContentBundle\View\Exception\ValidationException;
use KupShop\OrderingBundle\Entity\Purchase\ProductPurchaseItem;
use KupShop\ReservationBundle\Event\ReservationBeforeCreateEvent;
use KupShop\ReservationBundle\Event\ReservationCreatedEvent;
use KupShop\ReservationBundle\Util\ReservationUtil;
use KupShop\SellerBundle\Utils\SellerUtil;
use KupShop\StoresBundle\Utils\StoresInStore;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ReservationSubscriber implements EventSubscriberInterface
{
protected ReservationUtil $reservationUtil;
protected StoresInStore $storesInStore;
protected SellerUtil $sellerUtil;
public function __construct(ReservationUtil $reservationUtil, StoresInStore $storesInStore, SellerUtil $sellerUtil)
{
$this->reservationUtil = $reservationUtil;
$this->storesInStore = $storesInStore;
$this->sellerUtil = $sellerUtil;
}
public static function getSubscribedEvents(): array
{
return [
ReservationCreatedEvent::class => [
['mergeReservationsImmediately', 255],
],
ReservationBeforeCreateEvent::class => [
['checkItem', 255],
],
];
}
public function mergeReservationsImmediately(ReservationCreatedEvent $event): void
{
$dbcfg = \Settings::getDefault();
$mergeInterval = (int) ($dbcfg->reservations['merge_interval'] ?? 0);
if ($mergeInterval !== 0) {
return;
}
$orders = $this->reservationUtil->mergeReservationsIntoOrders([$event->reservation->id]);
if ($order = reset($orders)) {
// nastavim na objekt rezervace ID objednavky
$event->reservation->setIdOrder((int) $order->id);
// abych mohl v GTM pracovat s objektem objednavky
$event->reservation->setOrder($order);
}
}
public function checkItem(ReservationBeforeCreateEvent $event): void
{
$dbcfg = \Settings::getDefault();
if ($dbcfg->order_availability === \Settings::ORDER_AVAILABILITY_ALL) {
return;
}
// pokud nemam specifikovaneho sellera, tak nemuzu provest kontrolu
if (!($storeId = ($this->sellerUtil->getSeller((int) ($event->data['sellerId'] ?? null))['id_store'] ?? null))) {
throw new \RuntimeException('Cannot check item stock! Missing sellerId.');
}
$this->checkPurchaseItemStoreQuantity($event->purchaseItem, (int) $storeId);
}
protected function checkPurchaseItemStoreQuantity(ProductPurchaseItem $purchaseItem, int $storeId): void
{
$amounts = $this->storesInStore->getProductInStores(
(int) $purchaseItem->getIdProduct(),
$purchaseItem->getIdVariation() ? (int) $purchaseItem->getIdVariation() : null
);
$inStoreQuantity = (float) ($amounts[$storeId] ?? 0);
if ($inStoreQuantity < $purchaseItem->getPieces()) {
throw new ValidationException(translate('errorItemNotInStore', 'reservations'));
}
}
}