src/Controller/Action/SubscribeToNewsletterAction.php line 26

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Controller\Action;
  4. use App\Entity\Newsletter\NewsletterSubscribes;
  5. use App\Form\Type\Newsletter\SubscribeToNewsletterType;
  6. use App\Repository\Newsletter\NewsletterSubscribesRepository;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Sylius\Component\Channel\Context\ChannelContextInterface;
  9. use Sylius\Component\Locale\Context\LocaleContextInterface;
  10. use Symfony\Component\Form\FormError;
  11. use Symfony\Component\Form\FormFactoryInterface;
  12. use Symfony\Component\Form\FormInterface;
  13. use Symfony\Component\HttpFoundation\JsonResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Contracts\Translation\TranslatorInterface;
  17. use Twig\Environment;
  18. use SendinBlue\Client\Api\ContactsApi;
  19. use SendinBlue\Client\Configuration;
  20. use GuzzleHttp\Client as GuzzleClient;
  21. final class SubscribeToNewsletterAction
  22. {
  23.     private $sendinblueApiKey;
  24.     /** @var FormFactoryInterface */
  25.     private $formFactory;
  26.     /** @var Environment */
  27.     private $twig;
  28.     /** @var TranslatorInterface */
  29.     private $translator;
  30.     /** @var ChannelContextInterface */
  31.     private $channelContext;
  32.     private $newsletterSubscribesRepository;
  33.     private $localeContext;
  34.     private $em;
  35.     public function __construct(
  36.         string $sendinblueApiKey,
  37.         FormFactoryInterface $formFactory,
  38.         Environment $twig,
  39.         TranslatorInterface $translator,
  40.         ChannelContextInterface $channelContext,
  41.         NewsletterSubscribesRepository $newsletterSubscribesRepository,
  42.         LocaleContextInterface $localeContext,
  43.         EntityManagerInterface $em
  44.     ) {
  45.         $this->sendinblueApiKey $sendinblueApiKey;
  46.         $this->formFactory $formFactory;
  47.         $this->twig $twig;
  48.         $this->translator $translator;
  49.         $this->channelContext $channelContext;
  50.         $this->newsletterSubscribesRepository $newsletterSubscribesRepository;
  51.         $this->localeContext $localeContext;
  52.         $this->em $em;
  53.     }
  54.     public function __invoke(Request $request): Response
  55.     {
  56.         $form $this->formFactory->create(SubscribeToNewsletterType::class);
  57.         $form->handleRequest($request);
  58.         if ($form->isSubmitted()) {
  59.             if (!$form->isValid()) {
  60.                 $errors $this->getErrorsFromForm($form);
  61.                 if (is_string($errors)) {
  62.                     $errors = [$errors];
  63.                 }
  64.                 return $this->json(
  65.                     $this->translator->trans('setono_sylius_mailchimp.ui.an_error_occurred'),
  66.                     400,
  67.                     $errors
  68.                 );
  69.             }
  70.             $email $form->get('email')->getData() ?? '';
  71.             if (!filter_var($email\FILTER_VALIDATE_EMAIL)) {
  72.                 return $this->json(
  73.                     $this->translator->trans('setono_sylius_mailchimp.ui.an_error_occurred')
  74.                 );
  75.             }
  76.             $subscribe $this->newsletterSubscribesRepository->findOneBy(['mail' => $email]);
  77.             if ($subscribe === null) {
  78.                 $subscribe = new NewsletterSubscribes();
  79.                 $subscribe->setMail($email);
  80.                 $subscribe->setLocaleCode($this->localeContext->getLocaleCode());
  81.                 $this->em->persist($subscribe);
  82.                 $this->em->flush();
  83.             }
  84.             $config Configuration::getDefaultConfiguration()->setApiKey('api-key'$this->sendinblueApiKey);
  85.             $apiInstance = new ContactsApi(new GuzzleClient(), $config);
  86.             $contact = [
  87.                 'email' => $email,
  88.                 'listIds' => [8],
  89.                 'updateEnabled' => true,
  90.                 'attributes' => [
  91.                     'EMAIL' => $email,
  92.                 ],
  93.             ];
  94.             try {
  95.                 $apiInstance->createContact($contact);
  96.             } catch (\Exception $e) {
  97.                 return $this->json($this->translator->trans('Erreur lors de l\'inscription à la newsletter'), 500, [$e->getMessage()]);
  98.             }
  99.             return $this->json($this->translator->trans('setono_sylius_mailchimp.ui.subscribed_successfully'));
  100.         }
  101.         $template $request->query->get('template''@SetonoSyliusMailchimpPlugin/Shop/Subscribe/content.html.twig');
  102.         $content $this->twig->render($template, [
  103.             'form' => $form->createView(),
  104.         ]);
  105.         return new Response($content);
  106.     }
  107.     private function json(string $messageint $status 200, array $errors = []): JsonResponse
  108.     {
  109.         return new JsonResponse([
  110.             'message' => $message,
  111.             'errors' => $errors,
  112.         ], $status);
  113.     }
  114.     /**
  115.      * Taken from https://symfonycasts.com/screencast/javascript/post-proper-api-endpoint#codeblock-99cf6afd45.
  116.      *
  117.      * @return array|string
  118.      */
  119.     private function getErrorsFromForm(FormInterface $form)
  120.     {
  121.         /** @var FormError $error */
  122.         foreach ($form->getErrors() as $error) {
  123.             // only supporting 1 error per field
  124.             // and not supporting a "field" with errors, that has more
  125.             // fields with errors below it
  126.             return $error->getMessage();
  127.         }
  128.         $errors = [];
  129.         foreach ($form->all() as $childForm) {
  130.             $childError $this->getErrorsFromForm($childForm);
  131.             if (is_string($childError)) {
  132.                 $errors[$childForm->getName()] = $childError;
  133.             }
  134.         }
  135.         return $errors;
  136.     }
  137. }