src/EventSubscriber/Promotion/PromotionCodeAddCreditPacksSubscriber.php line 38

  1. <?php
  2. /*
  3.  * This file is part of the Pellipop project.
  4.  *
  5.  * (c) Mobizel
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace App\EventSubscriber\Promotion;
  12. use ApiPlatform\Symfony\EventListener\EventPriorities;
  13. use App\Entity\Promotion\PromotionCode;
  14. use App\Modifier\Product\CreditPackModifier;
  15. use Sylius\Component\Resource\Repository\RepositoryInterface;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpKernel\Event\ViewEvent;
  19. use Symfony\Component\HttpKernel\KernelEvents;
  20. class PromotionCodeAddCreditPacksSubscriber implements EventSubscriberInterface
  21. {
  22.     public function __construct(
  23.         private RepositoryInterface $creditPackRepository,
  24.         private CreditPackModifier $creditPackModifier,
  25.     ) {
  26.     }
  27.     public static function getSubscribedEvents()
  28.     {
  29.         return [ KernelEvents::VIEW => ['hydrateCreditPack'EventPriorities::PRE_SERIALIZE]];
  30.     }
  31.     public function hydrateCreditPack(ViewEvent $event): void
  32.     {
  33.         $promotionCode $event->getControllerResult();
  34.         $method $event->getRequest()->getMethod();
  35.         if (!$promotionCode instanceof PromotionCode || Request::METHOD_GET !== $method) {
  36.             return;
  37.         }
  38.         $creditPacks $this->creditPackRepository->findBy(['enabled' => true]);
  39.         
  40.         foreach ($creditPacks as $creditPack) {
  41.             $this->creditPackModifier->addPromotion($creditPack$promotionCode);
  42.             $promotionCode->addCreditPack($creditPack);
  43.         }
  44.     }
  45. }