<?php
namespace App\EventSubscriber\Bloc;
use App\Application\Sonata\MediaBundle\Entity\Media;
use App\Entity\Formulaire\Contact;
use App\Entity\Formulaire\Conversation;
use App\Entity\Formulaire\Message;
use App\Event\BlocEvent;
use App\Utils\Emails\ContactEmail;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Model\UserInterface;
use Symfony\Bundle\SwiftmailerBundle\EventListener\EmailSenderListener;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Psr\Log\LoggerInterface;
use Sonata\MediaBundle\Entity\MediaManager;
class BlocSubscriber implements EventSubscriberInterface
{
private $em;
private $contactEmail;
private $container;
private $logger;
private $mediaManager;
public function __construct(
EntityManagerInterface $entityManager,
ContactEmail $contactEmail,
ContainerInterface $container,
LoggerInterface $logger,
MediaManager $mediaManager
) {
$this->em = $entityManager;
$this->contactEmail = $contactEmail;
$this->container = $container;
$this->logger = $logger;
$this->mediaManager = $mediaManager;
}
public static function getSubscribedEvents()
{
return array(
BlocEvent::BLOC_INITIALIZE_FORM => array('onBlocInitializeForm', -10),
);
}
public function onBlocInitializeForm(BlocEvent $event)
{
$bloc = $event->getBloc();
$user = $event->getUser();
$produit = $event->getProduit();
$request = $event->getRequest();
// Override du titre et texte du bloc
if (
$bloc->getFormulaire() == Contact::FORM_CSE &&
$user instanceof UserInterface &&
false === $user->getGroups()->isEmpty()
) {
$userGroup = $user->getGroups()->first();
if (false === $userGroup->getAfficherFormulaire()) {
return;
}
$bloc->setTitre($userGroup->getTitreFormulaire());
$bloc->setTexte($userGroup->getTexteFormulaire());
}
$contact = new Contact();
$contact->setFormulaire($bloc->getFormulaire());
if ($user instanceof UserInterface) {
$contact->setUser($user);
}
if ($contact->getFormulaire() == Contact::FORM_PRODUIT && !is_null($produit)) {
$contact->setProduit($produit);
}
$className = 'App\\Form\\Type\\Formulaire\\'.$bloc->getFormulaire().'Type';
$form = $this->container->get('form.factory')->create($className, $contact);
$form->handleRequest($request);
if (!$form->isSubmitted()) {
if ($contact->getFormulaire() == Contact::FORM_PRODUIT && !is_null($produit)) {
$contact->setObjet($produit->getTitre());
}
if ($user instanceof UserInterface) {
$contact->setNom($user->getNom());
$contact->setPrenom($user->getPrenom());
$contact->setEmail($user->getEmail());
if (!is_null($user->getCivilite())) {
$contact->setCivilite($user->getCivilite());
}
if (!is_null($user->getTelephone())) {
$contact->setTelephone($user->getTelephone());
}
if (!is_null($user->getAdresse1())) {
$contact->setAdresse($user->getAdresse1());
}
if (!is_null($user->getCodePostal())) {
$contact->setCodePostal($user->getCodePostal());
}
if (!is_null($user->getVille())) {
$contact->setVille($user->getVille());
}
}
$form->setData($contact);
}
if ($form->isSubmitted() && $form->isValid()) {
if (
$contact->getFormulaire() == Contact::FORM_CONTACT ||
$contact->getFormulaire() == Contact::FORM_PRODUIT ||
$contact->getFormulaire() == Contact::FORM_CSE ||
$contact->getFormulaire() == Contact::FORM_MESSAGERIE
) {
$maxFichier = 2;
if ($contact->getFormulaire() == Contact::FORM_MESSAGERIE) {
$maxFichier = 1;
}
for ($i=1; $i<=$maxFichier; $i++) {
if ($form->has('fichier'.$i)) {
$fichier = $form->get('fichier'.$i)->getData();
if (!empty($fichier)) {
try {
$originalFilename = pathinfo($fichier->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$fichier->guessExtension();
$media = new Media();
$media->setBinaryContent($fichier);
$media->setContext('contact');
$media->setProviderName('sonata.media.provider.file');
$media->setEnabled(true);
$media->setName($newFilename);
$this->mediaManager->save($media);
$contact->{"setFichier$i"}($media);
}
catch (FileException $e) {
$form->get('fichier'.$i)->addError(new FormError('Une erreur est survenue lors de l\'enregistrement de la pièce jointe, veuillez réessayer'));
}
}
}
}
}
if ($contact->getFormulaire() == Contact::FORM_TOMBOLA) {
$participations = $this->em->getRepository(Contact::class)->findContacts(
false,
Contact::FORM_TOMBOLA,
$contact->getEmail()
);
if (0 == count($participations)) {
$this->em->persist($contact);
$this->em->flush();
$response = new RedirectResponse($request->getPathInfo().'?confirm=true');
$event->setResponse($response);
}
else {
$form->addError(new FormError('Vous avez déjà participé à la tombola !'));
}
}
if ($contact->getFormulaire() != Contact::FORM_TOMBOLA) {
if ($contact->getFormulaire() != Contact::FORM_MESSAGERIE) {
$this->em->persist($contact);
$this->em->flush();
$this->contactEmail->alerteContact($contact);
(new EmailSenderListener($this->container, $this->logger))->onTerminate();
}
if ($contact->getFormulaire() == Contact::FORM_MESSAGERIE) {
$contact->setEmail($user->getEmail());
$contact->setCivilite($user->getCivilite());
$contact->setNom($user->getNom());
$contact->setPrenom($user->getPrenom());
$conversations = $this->em->getRepository(Conversation::class)
->findConversations(false, $contact->getUser()->getId());
if (count($conversations)) {
$conversation = $conversations[0];
} else {
$conversation = new Conversation();
$conversation->setUser($contact->getUser());
}
$message = new Message();
$message->setUser($contact->getUser());
$message->setFichier($contact->getFichier1());
$message->setObjet($contact->getObjet());
$message->setMessage($contact->getMessage());
$conversation->setDernierMessage(new \DateTime());
$conversation->setNeedReply(true);
$conversation->addMessage($message);
$this->em->persist($conversation);
$this->em->flush();
$this->contactEmail->alerteMessage($contact, false);
(new EmailSenderListener($this->container, $this->logger))->onTerminate();
}
$response = new RedirectResponse($request->getPathInfo().'?confirm=true');
$event->setResponse($response);
}
}
$bloc->form = $form->createView();
}
}