src/EventSubscribers/Main/DiscountCodeSubscriber.php line 56

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscribers\Main;
  3. use App\Events\Main\DiscountCode\DiscountCodeErrorEvent;
  4. use App\Services\TranslationManager;
  5. use App\Twig\GoogleTagManagerExtension;
  6. use phpDocumentor\Reflection\Types\This;
  7. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpFoundation\RequestStack;
  11. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  12. use Symfony\Contracts\Translation\TranslatorInterface;
  13. /**
  14.  * Class DiscountCodeSubscriber
  15.  * @package App\EventSubscribers\Main
  16.  */
  17. class DiscountCodeSubscriber implements EventSubscriberInterface
  18. {
  19.     const
  20.         DISCOUNT_CODE_APPLY_ERROR 'discount_code_apply_error'
  21.     ;
  22.     private SessionInterface $session;
  23.     private ?Request $request;
  24.     /**
  25.      * DiscountCodeSubscriber constructor.
  26.      */
  27.     public function __construct(
  28.         private RequestStack $requestStack,
  29.         private TranslatorInterface $translator
  30.     ) {
  31.         $this->request $this->requestStack->getCurrentRequest();
  32.         if ($this->request instanceof Request) {
  33.             $this->session $this->request->getSession();
  34.         }
  35.     }
  36.     /**
  37.      * @return array
  38.      */
  39.     public static function getSubscribedEvents()
  40.     {
  41.         return array(
  42.             self::DISCOUNT_CODE_APPLY_ERROR => "discountCodeApplyError"
  43.         );
  44.     }
  45.     /**
  46.      * Process stuff when a discount code error was fired.
  47.      * @param DiscountCodeErrorEvent $event
  48.      */
  49.     public function discountCodeApplyError(DiscountCodeErrorEvent $event)
  50.     {
  51.         if ($event->getException() instanceof \Exception) {
  52.             $error $this->translator->trans($event->getException()->getMessage(), [], TranslationManager::TRANSLATION_DOMAIN_FLASH);
  53.         } else {
  54.             $error $this->translator->trans($event->getErrorText(), [], TranslationManager::TRANSLATION_DOMAIN_FLASH);
  55.         }
  56.         // insert the error to be treated by GTM
  57.         $this->session->set(GoogleTagManagerExtension::GTM_SESSION_PROMOCODE_EVENT_KEY$error);
  58.         $this->session->set(GoogleTagManagerExtension::GTM_SESSION_PROMOCODE_NAME_KEY$event->getDiscountCodeName());
  59.     }
  60. }