src/EventSubscriber/AreaSubscriber.php line 35

  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Symfony\EventListener\EventPriorities;
  4. use App\Document\Area\Area;
  5. use App\Document\Area\Table;
  6. use App\Document\Area\TablePosition;
  7. use Doctrine\ODM\MongoDB\DocumentManager;
  8. use Doctrine\ODM\MongoDB\MongoDBException;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpKernel\Event\ViewEvent;
  12. use Symfony\Component\HttpKernel\KernelEvents;
  13. /**
  14.  * @author Roméo Razafindrakoto <romeorazaf@myagency.mg>
  15.  */
  16. class AreaSubscriber implements EventSubscriberInterface
  17. {
  18.     public function __construct(private readonly DocumentManager $manager)
  19.     {
  20.     }
  21.     public static function getSubscribedEvents(): array
  22.     {
  23.         return [
  24.             KernelEvents::VIEW => ['createTables'EventPriorities::POST_WRITE],
  25.         ];
  26.     }
  27.     /**
  28.      * @throws MongoDBException
  29.      */
  30.     public function createTables(ViewEvent $event): void
  31.     {
  32.         $area $event->getControllerResult();
  33.         $method $event->getRequest()->getMethod();
  34.         if (!$area instanceof Area || Request::METHOD_POST !== $method) {
  35.             return;
  36.         }
  37.         $numberOfTables $area->getCapacity();
  38.         $areaName $area->getName();
  39.         for ($i 1$i <= $numberOfTables; ++$i) {
  40.             $table = (new Table())
  41.                 ->setCapacity(0)
  42.                 ->setName("$areaName - $i")
  43.                 ->setArea($area)
  44.             ;
  45.             $this->manager->persist($table);
  46.             $tablePosition = (new TablePosition())
  47.                 ->setArea($area)
  48.                 ->setPosition($i)
  49.                 ->setTable($table)
  50.             ;
  51.             $this->manager->persist($tablePosition);
  52.         }
  53.         $this->manager->flush();
  54.     }
  55. }