src/EventSubscriber/OrderTableSubscriber.php line 31
<?phpnamespace App\EventSubscriber;use ApiPlatform\Symfony\EventListener\EventPriorities;use App\Document\Area\Table;use App\Document\Event\Order;use Doctrine\ODM\MongoDB\DocumentManager;use Doctrine\ODM\MongoDB\MongoDBException;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpKernel\Event\ViewEvent;use Symfony\Component\HttpKernel\KernelEvents;class OrderTableSubscriber implements EventSubscriberInterface{public function __construct(private readonly DocumentManager $manager){}public static function getSubscribedEvents(): array{return [KernelEvents::VIEW => ['updateTableOccupiedPlace', EventPriorities::PRE_WRITE],];}/*** @throws MongoDBException*/public function updateTableOccupiedPlace(ViewEvent $event): void{$order = $event->getControllerResult();$method = $event->getRequest()->getMethod();if (!$order instanceof Order || Request::METHOD_POST !== $method) {return;}// Get the associated OrderTable entity for this order$orderTable = $order->getOrderTable();// Get the associated Table entity for this order$table = $orderTable->getTable();if (!$table instanceof Table) {return;}// Get the current number of people for this table$currentNumPeople = $table->getOccupiedPlace();// Add the number of people from this order to the current number of people for this table$numPeople = $orderTable->getPlaces();// Check if the selected table has enough capacityif ($table->getCapacity() < $numPeople) {throw new \InvalidArgumentException('The selected table does not have enough capacity for the number of people in the order.');}// Calculate the new number of people after reserving the table$newNumPlace = $currentNumPeople + $numPeople;// Check if the selected table has enough capacity for the new number of peopleif ($table->getCapacity() < $newNumPlace) {throw new \InvalidArgumentException('The selected table does not have enough capacity to accommodate the new number of people.');}$table->setOccupiedPlace($newNumPlace);// Save the updated table entity$this->manager->persist($table);$this->manager->flush();}}