<?php
namespace App\Controller\Newsletter;
use App\Services\NewsletterApiService;
use Exception;
use App\Form\NewsletterFormType;
use App\Services\RecaptchaService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Pimcore\Controller\FrontendController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
class NewsletterController extends FrontendController
{
/**
* @Template
* @Route("{lang}/newsletter-form/", name="newsletter-form")
* @param Request $request
* @param RecaptchaService $recaptchaService
* @param TranslatorInterface $translator
* @param NewsletterApiService $newsletterApi
* @param string|null $lang
* @return Response
*/
public function subscribeAction(
Request $request,
RecaptchaService $recaptchaService,
TranslatorInterface $translator,
NewsletterApiService $newsletterApi,
string $lang = null
): Response
{
$lang = $lang ?: $request->getLocale();
$form = $this->createForm(NewsletterFormType::class, [], [
'action' => $this->generateUrl('newsletter-form', ['lang' => $lang])
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$email = $data['email'];
$recaptcha = $recaptchaService->checkRecaptcha(
$request->get('newsletter-g-recaptcha-response'),
$request->getClientIp()
);
if ($recaptcha === RecaptchaService::INCORRECT_CAPTCHA) {
$error = $translator->trans('meddox.recaptcha.error');
return new JsonResponse(['error' => $error], 422);
}
return $newsletterApi->relayRequestToApi($email, action: NewsletterApiService::SUBSCRIBE_ACTION);
}
return $this->render('/segments/newsletter.html.twig', [
'form' => $form->createView(),
'fixedVersion' => $request->get('fixedVersion')
]);
}
/**
* @Template()
* @param Request $request
* @param NewsletterApiService $newsletterApi
* @return Response
* @throws Exception
*/
public function unsubscribeAction(
Request $request,
NewsletterApiService $newsletterApi,
): Response
{
$token = $request->get('token');
if ($token) {
$newsletterApi->relayRequestToApi($token, action: NewsletterApiService::UNSUBSCRIBE_ACTION);
}
return $this->render($this->document->getTemplate());
}
}