<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace App\Controller\Shop;
use Sylius\Bundle\CoreBundle\Form\Type\ContactType;
use Sylius\Bundle\ShopBundle\EmailManager\ContactEmailManagerInterface;
use Sylius\Component\Channel\Context\ChannelContextInterface;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Customer\Context\CustomerContextInterface;
use Sylius\Component\Locale\Context\LocaleContextInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use BitBag\SyliusCmsPlugin\Repository\PageRepository;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;
use Webmozart\Assert\Assert;
use Psr\Log\LoggerInterface;
use ReCaptcha\ReCaptcha;
use MailchimpMarketing;
final class ContactController
{
/** @var RouterInterface */
private $router;
/** @var FormFactoryInterface */
private $formFactory;
/** @var Environment */
private $templatingEngine;
/** @var ChannelContextInterface */
private $channelContext;
/** @var CustomerContextInterface */
private $customerContext;
/** @var LocaleContextInterface */
private $localeContext;
/** @var ContactEmailManagerInterface */
private $contactEmailManager;
/** @var PageRepository */
private $pageRepository;
/** @var ParameterBagInterface */
private $params;
/** @var LoggerInterface */
private $logger;
/** @var TranslatorInterface */
private $translator;
/**
* @param Environment $templatingEngine
*/
public function __construct(
RouterInterface $router,
FormFactoryInterface $formFactory,
Environment $templatingEngine,
ChannelContextInterface $channelContext,
CustomerContextInterface $customerContext,
LocaleContextInterface $localeContext,
ContactEmailManagerInterface $contactEmailManager,
PageRepository $pageRepository,
ParameterBagInterface $params,
LoggerInterface $logger,
TranslatorInterface $translator
) {
$this->router = $router;
$this->formFactory = $formFactory;
$this->templatingEngine = $templatingEngine;
$this->channelContext = $channelContext;
$this->customerContext = $customerContext;
$this->localeContext = $localeContext;
$this->contactEmailManager = $contactEmailManager;
$this->pageRepository = $pageRepository;
$this->params = $params;
$this->logger = $logger;
$this->translator = $translator;
}
public function requestAction(Request $request): Response
{
$formType = $this->getSyliusAttribute($request, 'form', ContactType::class);
$form = $this->formFactory->create($formType, null, $this->getFormOptions());
$localeCode = $this->localeContext->getLocaleCode();
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$data = $form->getData();
// Check the captcha token
$token = $request->request->get('recaptcha_token');
$recaptcha = new ReCaptcha($this->params->get('GOOGLE_RECAPTCHA_SECRET_KEY'));
$resp = $recaptcha->setExpectedHostname($_SERVER['SERVER_NAME'])
->verify($token, $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$errorMessage = $this->getSyliusAttribute(
$request,
'error_flash',
$this->translator->trans('sylius.contact.captcha_not_valid')
);
/** @var FlashBagInterface $flashBag */
$flashBag = $request->getSession()->getBag('flashes');
$flashBag->add('error', $errorMessage);
return new RedirectResponse($request->headers->get('referer'));
}
$channel = $this->channelContext->getChannel();
/** @var ChannelInterface $channel */
Assert::isInstanceOf($channel, ChannelInterface::class);
// $contactEmail = $channel->getContactEmail();
// WE SHOULD NOT SEND THE EMAIL CONDITIONALLY.
// WE SHOULD ALWAYS SEND IT TO THE HEADQUARTERS
// HENCE, WE'RE USING .ENV PARAM TO SET THIS CONTACT EMAIL
switch ($data['subject']) {
case 'sylius.ui.subjects.product_information_request':
$contactEmail = $this->params->get('product_information_email');
break;
case 'sylius.ui.subjects.event_quote_request':
$contactEmail = $this->params->get('quote_request_email');
break;
case 'sylius.ui.subjects.training_information_request':
$contactEmail = $this->params->get('information_request_email');
break;
case 'sylius.ui.subjects.order_information_request':
$contactEmail = $this->params->get('order_help_email');
break;
case 'sylius.ui.subjects.other_subjects':
$contactEmail = $this->params->get('contact_email');
break;
default:
$contactEmail = $this->params->get('contact_email');
break;
}
$currentUrl = $request->request->get('url');
if (null === $contactEmail) {
$errorMessage = $this->getSyliusAttribute(
$request,
'error_flash',
$this->translator->trans('sylius.contact.request_error')
);
/** @var FlashBagInterface $flashBag */
$flashBag = $request->getSession()->getBag('flashes');
$flashBag->add('error', $errorMessage);
return new RedirectResponse($request->headers->get('referer'));
}
$this->contactEmailManager->sendContactRequest($data, [$contactEmail], $channel, $localeCode);
$mailchimpApiKey = $channel->getMailchimpApiKey();
/* MailChimp ajout a la liste */
if ($data["subscribedToNewsletter"] && isset($mailchimpApiKey) && !empty($mailchimpApiKey))
{
//https://mailchimp.com/developer/marketing/api/list-members/
try {
$mcr = true;
$mailchimp = new MailchimpMarketing\ApiClient();
$mailchimp->setConfig([
'apiKey' => $channel->getMailchimpApiKey(),
'server' => $channel->getMailchimpServer(),
]);
}
catch (\EXCEPTION $e) {
$mcr = false;
}
$listId = $channel->getMailchimpListId ();
if ( $mcr && isset($listId) && !empty($listId) )
{
try {
$response = $mailchimp->lists->addListMember($listId, [
"email_address" => strtolower($data["email"]),
"status" => "subscribed",
]);
}
catch (\EXCEPTION $e) {
}
}
}
$successMessage = $this->getSyliusAttribute(
$request,
'success_flash',
$this->translator->trans('sylius.contact.request_success')
);
/** @var FlashBagInterface $flashBag */
$flashBag = $request->getSession()->getBag('flashes');
$flashBag->add('success', $successMessage);
// $redirectRoute = $this->getSyliusAttribute($request, 'redirect', 'referer');
return new RedirectResponse($currentUrl);
}
// Identify the page calling this endpoint to define which template to load
$urlSegments = explode("/", $_SERVER['REQUEST_URI']);
if(isset($urlSegments[2]) && isset($urlSegments[3]) && ($urlSegments[2] === "page")) {
$channel = $this->channelContext->getChannel();
$page = $this->pageRepository->findOneEnabledBySlugAndChannelCode($urlSegments[3], $urlSegments[1], $channel->getCode());
$pageSlug = "/" . $localeCode . "/page/" . $page->getSlug();
switch ($page->getCode()) {
case 'fromagers-evenementiels':
$template = $this->getSyliusAttribute($request, 'template', '@SyliusShop/Contact/contact-request-service.html.twig');
break;
case 'centre-international-mons-formation':
$template = $this->getSyliusAttribute($request, 'template', '@SyliusShop/Contact/contact-request-training.html.twig');
break;
case 'contact':
default:
$template = $this->getSyliusAttribute($request, 'template', '@SyliusShop/Contact/request.html.twig');
break;
}
}
else {
$template = $this->getSyliusAttribute($request, 'template', '@SyliusShop/Contact/request.html.twig');
$pageSlug = "/" . $localeCode;
}
return new Response($this->templatingEngine->render($template, ['form' => $form->createView(), 'url' => $pageSlug]));
}
private function getSyliusAttribute(Request $request, string $attributeName, ?string $default): ?string
{
$attributes = $request->attributes->get('_sylius');
return $attributes[$attributeName] ?? $default;
}
private function getFormOptions(): array
{
$customer = $this->customerContext->getCustomer();
if (null === $customer) {
return [];
}
return ['email' => $customer->getEmail()];
}
}