<?php
namespace App\EventSubscribers\Main;
use App\Events\Main\DiscountCode\DiscountCodeErrorEvent;
use App\Services\TranslationManager;
use App\Twig\GoogleTagManagerExtension;
use phpDocumentor\Reflection\Types\This;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Class DiscountCodeSubscriber
* @package App\EventSubscribers\Main
*/
class DiscountCodeSubscriber implements EventSubscriberInterface
{
const
DISCOUNT_CODE_APPLY_ERROR = 'discount_code_apply_error'
;
private SessionInterface $session;
private ?Request $request;
/**
* DiscountCodeSubscriber constructor.
*/
public function __construct(
private RequestStack $requestStack,
private TranslatorInterface $translator
) {
$this->request = $this->requestStack->getCurrentRequest();
if ($this->request instanceof Request) {
$this->session = $this->request->getSession();
}
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return array(
self::DISCOUNT_CODE_APPLY_ERROR => "discountCodeApplyError"
);
}
/**
* Process stuff when a discount code error was fired.
* @param DiscountCodeErrorEvent $event
*/
public function discountCodeApplyError(DiscountCodeErrorEvent $event)
{
if ($event->getException() instanceof \Exception) {
$error = $this->translator->trans($event->getException()->getMessage(), [], TranslationManager::TRANSLATION_DOMAIN_FLASH);
} else {
$error = $this->translator->trans($event->getErrorText(), [], TranslationManager::TRANSLATION_DOMAIN_FLASH);
}
// insert the error to be treated by GTM
$this->session->set(GoogleTagManagerExtension::GTM_SESSION_PROMOCODE_EVENT_KEY, $error);
$this->session->set(GoogleTagManagerExtension::GTM_SESSION_PROMOCODE_NAME_KEY, $event->getDiscountCodeName());
}
}