src/EventSubscriber/AcheterEventSubscriber.php line 27

  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Acheter;
  4. use App\Service\NotificationService;
  5. use ApiPlatform\Symfony\EventListener\EventPriorities;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpKernel\Event\ViewEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. class AcheterEventSubscriber implements EventSubscriberInterface
  11. {
  12.     public function __construct(
  13.         private NotificationService $notificationService
  14.     ) {
  15.     }
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             KernelEvents::VIEW => ['createNotification'EventPriorities::POST_WRITE],
  20.         ];
  21.     }
  22.     public function createNotification(ViewEvent $event): void
  23.     {
  24.         $acheter $event->getControllerResult();
  25.         $method $event->getRequest()->getMethod();
  26.         // Ne traiter que les requêtes POST pour créer une notification
  27.         if (!$acheter instanceof Acheter || Request::METHOD_POST !== $method) {
  28.             return;
  29.         }
  30.         // Vérifier que l'achat a bien été créé (a un ID)
  31.         if (!$acheter->getId()) {
  32.             return;
  33.         }
  34.         try {
  35.             $user $acheter->getClient();
  36.             if (!$user) {
  37.                 return;
  38.             }
  39.             // Récupérer les informations du pack
  40.             $pack $acheter->getPackAcheter();
  41.             if (!$pack) {
  42.                 return;
  43.             }
  44.             // Calculer le montant total (on suppose qu'on crée un seul achat à la fois via l'API)
  45.             // Si plusieurs achats sont créés, chaque création déclenchera une notification
  46.             $montantPack = (float) $pack->getMontantPack();
  47.             
  48.             // Créer la notification
  49.             $this->notificationService->createPurchaseNotification(
  50.                 $user,
  51.                 1// nombre de packs (1 par appel API)
  52.                 $montantPack
  53.             );
  54.         } catch (\Exception $e) {
  55.             // Logger l'erreur mais ne pas faire échouer la requête
  56.             error_log('Erreur création notification achat (EventSubscriber): ' $e->getMessage());
  57.         }
  58.     }
  59. }