<?php
namespace App\Controller\ContactUs;
use App\DataMapper\ContactUs\ContactUsDataMapper;
use App\Form\ContactUsFormType;
use App\Repository\ContactUsRepository;
use App\Services\RecaptchaService;
use Exception;
use Pimcore\Controller\FrontendController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
class ContactUsController extends FrontendController
{
/**
* @Template
* @Route("{lang}/contact-us-form/", name="contact-us")
*
* @param Request $request
* @param ContactUsRepository $contactUsRepository
* @param RecaptchaService $recaptchaService
* @param TranslatorInterface $translator
* @param string|null $lang
* @return Response
* @throws Exception
*/
public function postContactUsAction (
Request $request,
ContactUsRepository $contactUsRepository,
RecaptchaService $recaptchaService,
TranslatorInterface $translator,
string $lang = null
) : Response {
$lang = $lang ?: $request->getLocale();
$form = $this->createForm(ContactUsFormType::class, [], [
'action' => $this->generateUrl('contact-us', ['lang' => $lang])
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$recaptcha = $recaptchaService->checkRecaptcha(
$request->get('contact-us-g-recaptcha-response'),
$request->getClientIp()
);
if ($recaptcha === RecaptchaService::INCORRECT_CAPTCHA) {
$error = $translator->trans('meddox.recaptcha.error');
return new JsonResponse(['error' => $error], 422);
}
$contactUsObject = $contactUsRepository->createContactUsObject($data);
$contactUsMapped = (new ContactUsDataMapper($contactUsObject))->toArray($request);
return new JsonResponse(['contactUsObject' => $contactUsMapped], 200);
}
return $this->render("/segments/contact-us.html.twig", [
'form' => $form->createView()
]);
}
}