src/EventSubscriber/OrderTableSubscriber.php line 31

  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Symfony\EventListener\EventPriorities;
  4. use App\Document\Area\Table;
  5. use App\Document\Event\Order;
  6. use Doctrine\ODM\MongoDB\DocumentManager;
  7. use Doctrine\ODM\MongoDB\MongoDBException;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpKernel\Event\ViewEvent;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. class OrderTableSubscriber implements EventSubscriberInterface
  13. {
  14.     public function __construct(private readonly DocumentManager $manager)
  15.     {
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             KernelEvents::VIEW => ['updateTableOccupiedPlace'EventPriorities::PRE_WRITE],
  21.         ];
  22.     }
  23.     /**
  24.      * @throws MongoDBException
  25.      */
  26.     public function updateTableOccupiedPlace(ViewEvent $event): void
  27.     {
  28.         $order $event->getControllerResult();
  29.         $method $event->getRequest()->getMethod();
  30.         if (!$order instanceof Order || Request::METHOD_POST !== $method) {
  31.             return;
  32.         }
  33.         // Get the associated OrderTable entity for this order
  34.         $orderTable $order->getOrderTable();
  35.         // Get the associated Table entity for this order
  36.         $table $orderTable->getTable();
  37.         if (!$table instanceof Table) {
  38.             return;
  39.         }
  40.         // Get the current number of people for this table
  41.         $currentNumPeople $table->getOccupiedPlace();
  42.         // Add the number of people from this order to the current number of people for this table
  43.         $numPeople $orderTable->getPlaces();
  44.         // Check if the selected table has enough capacity
  45.         if ($table->getCapacity() < $numPeople) {
  46.             throw new \InvalidArgumentException('The selected table does not have enough capacity for the number of people in the order.');
  47.         }
  48.         // Calculate the new number of people after reserving the table
  49.         $newNumPlace $currentNumPeople $numPeople;
  50.         // Check if the selected table has enough capacity for the new number of people
  51.         if ($table->getCapacity() < $newNumPlace) {
  52.             throw new \InvalidArgumentException('The selected table does not have enough capacity to accommodate the new number of people.');
  53.         }
  54.         $table->setOccupiedPlace($newNumPlace);
  55.         // Save the updated table entity
  56.         $this->manager->persist($table);
  57.         $this->manager->flush();
  58.     }
  59. }