em = $em ; $this->userRepository = $userRepository ; $this->newsletterRepository = $newsletterRepository ; $this->globalParam = $globalParam ; } public function subscribe(Request $request, UserManipulator $userManipulator) { $form = $this->createForm(NewsletterType::class); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $data = $form->getData() ; $email = $data['email'] ; $userExist = $this->userRepository->findOneBy(['email' => $email]) ; $newsletter = $this->globalParam->getCurrentMerchant()->getNewsletter() ; if($newsletter) { $userSubscribe = false ; if($userExist) { if($this->getUser() && $userExist && $this->getUser() == $userExist) { if($userExist->getNewsletters()->contains($newsletter)) { $this->addFlash('error','Vous êtes déjà inscrit à cette newsletter.'); } else { $userExist->addNewsletter($newsletter) ; $userSubscribe = true ; $this->em->persist($userExist); } } else { $form->get('email')->addError(new FormError('Cette adresse email est déjà utilisée')) ; } } else { $user = $userManipulator->create($email, '9e438d8a7b036ea9b8d4375377d47e1a', $email, false, false) ; $user->addNewsletter($newsletter) ; $user->addRole('ROLE_NEWSLETTER') ; $this->em->persist($user); $userSubscribe = true ; } if($userSubscribe) { $this->addFlash('success','Vous avez bien été ajouté à la newsletter.'); $this->em->flush() ; return $this->redirectToRoute('frontend_newsletter_subscribe') ; } } else { throw new \ErrorException('Aucune newsletter définie.') ; } } return $this->render('frontend/site/newsletter.html.twig', [ 'form' => $form->createView() ]); } public function unsubscribe($idUser, $idNewsletter) { $user = $this->userRepository->find($idUser) ; $newsletter = $this->newsletterRepository->find($idNewsletter) ; if(!$user) { throw new NotFoundHttpException('Utilisateur introuvable') ; } if(!$newsletter) { throw new NotFoundHttpException('Newsletter introuvable') ; } if($user->getNewsletters()->contains($newsletter)) { $user->removeNewsletter($newsletter) ; $this->em->persist($user); $this->em->flush() ; return $this->render('frontend/site/newsletter_confirm_unsubscribe.html.twig'); } return $this->redirectToRoute('frontend_index') ; } }