Browse Source

Merge branch 'develop'

master^2
Fab 3 years ago
parent
commit
4420a36635
15 changed files with 435 additions and 212 deletions
  1. +9
    -11
      ShopBundle/Controller/Backend/AdminController.php
  2. +73
    -63
      ShopBundle/Controller/Backend/NewsController.php
  3. +17
    -0
      ShopBundle/Form/Backend/Common/EntityType.php
  4. +42
    -0
      ShopBundle/Form/Backend/Common/NewslettersType.php
  5. +41
    -0
      ShopBundle/Form/DataTransformer/NewsletterSignupToBooleanTransformer.php
  6. +14
    -8
      ShopBundle/Form/Frontend/RegistrationType.php
  7. +9
    -3
      ShopBundle/Manager/EntityManager.php
  8. +6
    -2
      ShopBundle/Model/Merchant.php
  9. +17
    -0
      ShopBundle/Model/Newsletter.php
  10. +6
    -1
      ShopBundle/Resources/public/js/backend/script/default/init-list.js
  11. +1
    -0
      ShopBundle/Resources/translations/lcshop.fr.yaml
  12. +81
    -0
      ShopBundle/Services/MailjetSMS.php
  13. +104
    -123
      ShopBundle/Services/UserUtils.php
  14. +13
    -0
      ShopBundle/Services/Utils.php
  15. +2
    -1
      ShopBundle/Twig/FrontendTwigExtension.php

+ 9
- 11
ShopBundle/Controller/Backend/AdminController.php View File

if ($filter !== null) { if ($filter !== null) {
if ($this->utils->hasFilterAssociation($field['initProperty'])) { if ($this->utils->hasFilterAssociation($field['initProperty'])) {
$aliasRelation = $this->utils->getFilterAssociationAlias($field['initProperty']); $aliasRelation = $this->utils->getFilterAssociationAlias($field['initProperty']);
if(array_search($aliasRelation, $queryBuilder->getAllAliases())===false){
$queryBuilder->innerJoin('entity.'.$aliasRelation, $aliasRelation);
if (array_search($aliasRelation, $queryBuilder->getAllAliases()) === false) {
$queryBuilder->innerJoin('entity.' . $aliasRelation, $aliasRelation);
} }
$queryBuilder->andWhere($field['initProperty'] . ' LIKE :' . $field['property'] . ''); $queryBuilder->andWhere($field['initProperty'] . ' LIKE :' . $field['property'] . '');
$queryBuilder->setParameter($field['property'], '%' . $filter . '%'); $queryBuilder->setParameter($field['property'], '%' . $filter . '%');
if ($filter !== null) { if ($filter !== null) {


//TODO Faut généraliser avec TreeInterface, ça ne doit pas être ici //TODO Faut généraliser avec TreeInterface, ça ne doit pas être ici
if($field['property'] == 'productCategories') {
if ($field['property'] == 'productCategories') {


$queryBuilder->andWhere(':' . $field['property'] . ' MEMBER OF entity.' . $field['property'].' OR product_categories.parent = :' . $field['property']);
$queryBuilder->andWhere(':' . $field['property'] . ' MEMBER OF entity.' . $field['property'] . ' OR product_categories.parent = :' . $field['property']);
$queryBuilder->setParameter($field['property'], $filter); $queryBuilder->setParameter($field['property'], $filter);
}
else {
} else {
if ($field['type_options']['multiple']) { if ($field['type_options']['multiple']) {
$queryBuilder->andWhere(':' . $field['property'] . ' MEMBER OF entity.' . $field['property'] . ''); $queryBuilder->andWhere(':' . $field['property'] . ' MEMBER OF entity.' . $field['property'] . '');
}
else {
} else {
$queryBuilder->andWhere('entity.' . $field['property'] . ' = :' . $field['property'] . ''); $queryBuilder->andWhere('entity.' . $field['property'] . ' = :' . $field['property'] . '');
} }


if ($filter instanceof TreeInterface && $filter->getParent() == null) { if ($filter instanceof TreeInterface && $filter->getParent() == null) {
$queryBuilder->setParameter($field['property'], array_merge(array($filter), $filter->getChildrens()->toArray())); $queryBuilder->setParameter($field['property'], array_merge(array($filter), $filter->getChildrens()->toArray()));
}
else {
} else {
$queryBuilder->setParameter($field['property'], $filter); $queryBuilder->setParameter($field['property'], $filter);
} }
} }
$isFilterMerchantInterface = in_array('Lc\ShopBundle\Context\FilterMerchantInterface', $classImplements); $isFilterMerchantInterface = in_array('Lc\ShopBundle\Context\FilterMerchantInterface', $classImplements);
$isFilterMultipleMerchantsInterface = in_array('Lc\ShopBundle\Context\FilterMultipleMerchantsInterface', $classImplements); $isFilterMultipleMerchantsInterface = in_array('Lc\ShopBundle\Context\FilterMultipleMerchantsInterface', $classImplements);


if ($isFilterMerchantInterface || $isFilterMultipleMerchantsInterface) {
if (($isFilterMerchantInterface || $isFilterMultipleMerchantsInterface) && (!isset($passedOptions['merchant_filter']) || $passedOptions['merchant_filter'] === true)) {



if (in_array('Lc\ShopBundle\Context\StatusInterface', $classImplements)) { if (in_array('Lc\ShopBundle\Context\StatusInterface', $classImplements)) {
$statusInterface = true; $statusInterface = true;

+ 73
- 63
ShopBundle/Controller/Backend/NewsController.php View File

public function sendTestAction() public function sendTestAction()
{ {
$newsletter = $this->getNewsletter() ; $newsletter = $this->getNewsletter() ;
$news = $this->getNews() ;


$merchantCurrent = $this->merchantUtils->getMerchantCurrent() ;
$merchantConfigEmailContact = $merchantCurrent->getMerchantConfig('email-contact');
if($newsletter) {
$news = $this->getNews() ;

$merchantCurrent = $this->merchantUtils->getMerchantCurrent() ;
$merchantConfigEmailContact = $merchantCurrent->getMerchantConfig('email-contact');


if($merchantConfigEmailContact && strlen($merchantConfigEmailContact)) {
if($merchantConfigEmailContact && strlen($merchantConfigEmailContact)) {
$this->mailUtils->send([ $this->mailUtils->send([
MailUtils::SUBJECT => $news->getTitle(),
MailUtils::TO_EMAIL => $merchantConfigEmailContact,
MailUtils::TO_NAME => $this->parameterBag->get('app.site_name'),
MailUtils::CONTENT_TEMPLATE => 'mail/news',
MailUtils::CONTENT_DATA => [
'news' => $news,
'newsletter' => $newsletter,
'user' => $this->security->getUser()
],
MailUtils::SUBJECT => $news->getTitle(),
MailUtils::TO_EMAIL => $merchantConfigEmailContact,
MailUtils::TO_NAME => $this->parameterBag->get('app.site_name'),
MailUtils::CONTENT_TEMPLATE => 'mail/news',
MailUtils::CONTENT_DATA => [
'news' => $news,
'newsletter' => $newsletter,
'user' => $this->security->getUser()
],
]); ]);


$this->addFlash('success', 'Actualité de test envoyée à '.$merchantConfigEmailContact); $this->addFlash('success', 'Actualité de test envoyée à '.$merchantConfigEmailContact);
}
else {
}
else {
throw new \ErrorException("L'email de contact n'est pas défini pour ce Merchant.") ; throw new \ErrorException("L'email de contact n'est pas défini pour ce Merchant.") ;
}
} }


return $this->redirectToRoute('easyadmin', ['entity' => 'News', 'action' => 'list']) ; return $this->redirectToRoute('easyadmin', ['entity' => 'News', 'action' => 'list']) ;


$currentMerchant = $this->merchantUtils->getMerchantCurrent() ; $currentMerchant = $this->merchantUtils->getMerchantCurrent() ;
$newsletter = $this->getNewsletter() ; $newsletter = $this->getNewsletter() ;
$news = $this->getNews() ;
$users = $this->em->getRepository($this->em->getClassMetadata(UserInterface::class)->getName())->findAllByNewsletter($newsletter) ;


$countUsers = count($users) ;
if($newsletter) {
$news = $this->getNews() ;
$users = $this->em->getRepository($this->em->getClassMetadata(UserInterface::class)->getName())->findAllByNewsletter($newsletter) ;


$packageMessagesArray = [];
$packageMessageLimit = 50 ;
$countUsers = count($users) ;


$paramsTemplate = [
$packageMessagesArray = [];
$packageMessageLimit = 50 ;

$paramsTemplate = [
'news' => $news, 'news' => $news,
'newsletter' => $newsletter, 'newsletter' => $newsletter,
'user' => $this->security->getUser() 'user' => $this->security->getUser()
] ;
] ;


$i = 0 ;
$i = 0 ;


foreach ($users as $user) {
foreach ($users as $user) {
$paramsTemplate['user'] =$user; $paramsTemplate['user'] =$user;


if(!isset($packageMessagesArray[$i])) { if(!isset($packageMessagesArray[$i])) {
$packageMessagesArray[$i] = [] ;
$packageMessagesArray[$i] = [] ;
} }


if($user->getEmail() && strlen($user->getEmail())) { if($user->getEmail() && strlen($user->getEmail())) {
$packageMessagesArray[$i][] = [
'To' => [
[
'Email' => $user->getEmail(),
'Name' => $user->getFirstname().' '.$user->getLastname(),
]
],
'From' => [
'Email' => $this->getParameter('app.noreply_email'),
'Name' => $this->getParameter('app.site_name')
],
'Subject' => $currentMerchant->getMerchantConfig('email-subject-prefix').' '.$news->getTitle(),
'TextPart' => $this->renderView('mail/news-text.html.twig', $paramsTemplate),
'HTMLPart' => $this->renderView('mail/news-html.html.twig', $paramsTemplate),
'CustomCampaign' => $news->getTitle(),
'DeduplicateCampaign' => true
] ;
if(count($packageMessagesArray[$i]) >= $packageMessageLimit) {
$i ++ ;
}
$packageMessagesArray[$i][] = [
'To' => [
[
'Email' => $user->getEmail(),
'Name' => $user->getFirstname().' '.$user->getLastname(),
]
],
'From' => [
'Email' => $this->getParameter('app.noreply_email'),
'Name' => $this->getParameter('app.site_name')
],
'Subject' => $currentMerchant->getMerchantConfig('email-subject-prefix').' '.$news->getTitle(),
'TextPart' => $this->renderView('mail/news-text.html.twig', $paramsTemplate),
'HTMLPart' => $this->renderView('mail/news-html.html.twig', $paramsTemplate),
'CustomCampaign' => $news->getTitle(),
'DeduplicateCampaign' => true
] ;
if(count($packageMessagesArray[$i]) >= $packageMessageLimit) {
$i ++ ;
}
} }
}
}


if($countUsers > 0) {
if($countUsers > 0) {
$mj = new \Mailjet\Client($this->mailjetTransport->getApiKey(), $this->mailjetTransport->getApiSecret(),true,['version' => 'v3.1']); $mj = new \Mailjet\Client($this->mailjetTransport->getApiKey(), $this->mailjetTransport->getApiSecret(),true,['version' => 'v3.1']);


foreach($packageMessagesArray as $messagesArray) { foreach($packageMessagesArray as $messagesArray) {
$body = [
'Messages' => $messagesArray
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
$body = [
'Messages' => $messagesArray
];
$response = $mj->post(Resources::$Email, ['body' => $body]);
} }


if(isset($response) && $response->success()) { if(isset($response) && $response->success()) {
$this->addFlash('success', 'Actualité envoyée à '.$countUsers.' utilisateurs.');
$this->addFlash('success', 'Actualité envoyée à '.$countUsers.' utilisateurs.');


$news->setIsSent(true) ;
$this->em->persist($news);
$this->em->flush() ;
$news->setIsSent(true) ;
$this->em->persist($news);
$this->em->flush() ;
} }
else { else {
$this->addFlash('error', "Une erreur est survenue lors de l'envoi de l'actualité.");
$this->addFlash('error', "Une erreur est survenue lors de l'envoi de l'actualité.");
} }
}
else {
}
else {
$this->addFlash('error', 'Aucun utilisateur inscrit à la newsletter.'); $this->addFlash('error', 'Aucun utilisateur inscrit à la newsletter.');
}
} }


return $this->redirectToRoute('easyadmin', ['entity' => 'News', 'action' => 'list']) ; return $this->redirectToRoute('easyadmin', ['entity' => 'News', 'action' => 'list']) ;


public function getNewsletter() public function getNewsletter()
{ {
$newsletter = $this->merchantUtils->getMerchantCurrent()->getNewsletter() ;
$news = $this->getNews() ;


if($newsletter) {
return $newsletter ;
if($news) {
$newsletter = $news->getNewsletter() ;
}

if(isset($newsletter) && $newsletter) {
return $newsletter ;
} }
else { else {
throw new \ErrorException('Aucune newsletter n\'est liée à ce Merchant.') ;
$this->utils->addFlash('error', 'Aucune newsletter n\'est liée à l\'actualité.');
} }
} }



+ 17
- 0
ShopBundle/Form/Backend/Common/EntityType.php View File

<?php

namespace Lc\ShopBundle\Form\Backend\Common;

use Symfony\Bridge\Doctrine\Form\Type\EntityType as DefaultEntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class EntityType extends DefaultEntityType
{
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver->setDefaults([
'merchant_filter' => true
]);
}
}

+ 42
- 0
ShopBundle/Form/Backend/Common/NewslettersType.php View File

<?php

namespace Lc\ShopBundle\Form\Backend\Common;

use Doctrine\ORM\EntityManagerInterface;

use Lc\ShopBundle\Context\NewsletterInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;

class NewslettersType extends AbstractType
{
protected $em;
public function __construct(EntityManagerInterface $entityManager){
$this->em = $entityManager;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$builder = $event->getForm()->getParent();
$newsletterClass = $this->em->getClassMetadata(NewsletterInterface::class);

$builder->add('newsletters', EntityType::class, [
'class' => $newsletterClass->getName(),
'multiple' =>true,
'required' => false,
'merchant_filter'=> false
]);
});
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'merchant_filter' => false
]);
}
}

+ 41
- 0
ShopBundle/Form/DataTransformer/NewsletterSignupToBooleanTransformer.php View File

<?php

namespace Lc\ShopBundle\Form\DataTransformer;

use Lc\ShopBundle\Context\ProductInterface;
use Doctrine\ORM\EntityManagerInterface;
use Lc\ShopBundle\Services\UtilsManager;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Security\Core\Security;

class NewsletterSignupToBooleanTransformer implements DataTransformerInterface
{
private $security ;
private $userUtils ;

public function __construct(Security $security, UtilsManager $utilsManager)
{
$this->security = $security;
$this->userUtils = $utilsManager->getUserUtils() ;
}

public function transform($newsletter)
{
$user = $this->security->getUser() ;

if($user && $newsletter) {
return $this->userUtils->isSubscribedToNewsletter($user, $newsletter) ;
}

return false ;
}

public function reverseTransform($isSubscribed)
{
// Impossible de retrouver la newsletter depuis sa valeur booléenne.
//throw new TransformationFailedException('Impossible de retrouver la newsletter depuis sa valeur booléenne.') ;

return false ;
}
}

+ 14
- 8
ShopBundle/Form/Frontend/RegistrationType.php View File

public function __construct(UtilsManager $utilsManager) public function __construct(UtilsManager $utilsManager)
{ {
$this->utils = $utilsManager->getUtils() ; $this->utils = $utilsManager->getUtils() ;
$this->merchantUtils = $utilsManager->getMerchantUtils() ;
} }


public function getParent() public function getParent()


public function buildForm(FormBuilderInterface $builder, array $options) public function buildForm(FormBuilderInterface $builder, array $options)
{ {
$newsletters = $this->merchantUtils->getMerchantCurrent()->getNewsletters() ;

$builder->remove('username') $builder->remove('username')
->add('gender', ChoiceType::class, [ ->add('gender', ChoiceType::class, [
'label' => 'field.default.title', 'label' => 'field.default.title',
->add('phone', TextType::class, [ ->add('phone', TextType::class, [
'label' => 'field.default.phone', 'label' => 'field.default.phone',
'translation_domain' => 'lcshop', 'translation_domain' => 'lcshop',
])
->add('subscribeNewsletter', CheckboxType::class, [
'data' => true,
'label' => 'field.default.subscribeNewsletter',
'required' => false,
'mapped' => false,
'translation_domain' => 'lcshop',
'help' => 'Un seul mail par semaine qui annonce l’ouverture des ventes, les nouveautés et promotions de la semaine ainsi que des informations utiles.'
]); ]);


foreach($newsletters as $newsletter) {
$builder->add('newsletter_'.$newsletter->getId(), CheckboxType::class, [
//'label' => 'field.default.subscribeNewsletter',
'label' => $newsletter->getTitle(),
'required' => false,
'mapped' => false,
'translation_domain' => 'lcshop',
'help' => $newsletter->getDescription()
]);
}

// captcha // captcha
$this->utils->addCaptchaType($builder); $this->utils->addCaptchaType($builder);
} }

+ 9
- 3
ShopBundle/Manager/EntityManager.php View File

protected $security; protected $security;
protected $userSystem = null; protected $userSystem = null;


public function __construct(EventDispatcherInterface $eventDispatcher, EntityManagerInterface $entityManager, Security $security)
public function __construct(EventDispatcherInterface $eventDispatcher, EntityManagerInterface $entityManager,
Security $security)
{ {
$this->eventDispatcher = $eventDispatcher; $this->eventDispatcher = $eventDispatcher;
$this->entityManager = $entityManager; $this->entityManager = $entityManager;
{ {


if ($this->security->getUser() === null) { if ($this->security->getUser() === null) {
$entity->setUpdatedBy($this->getUserSystem());
$entity->setCreadtedBy($this->getUserSystem());
if(method_exists($entity, 'setUpdatedBy')) {
$entity->setUpdatedBy($this->getUserSystem());
}
if(method_exists($entity, 'setCreadtedBy')) {
$entity->setCreadtedBy($this->getUserSystem());
}
} }

$this->persist($entity); $this->persist($entity);
$this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::CREATE_EVENT); $this->eventDispatcher->dispatch(new EntityManagerEvent($entity), EntityManagerEvent::CREATE_EVENT);
return $this; return $this;

+ 6
- 2
ShopBundle/Model/Merchant.php View File

public function getNewsletter() public function getNewsletter()
{ {
$newsletters = $this->getNewsletters() ; $newsletters = $this->getNewsletters() ;
if(isset($newsletters[0])) {
return $newsletters[0] ;

foreach($newsletters as $newsletter) {
if($newsletter->getIsMain()) {
return $newsletter ;
}
} }

return false ; return false ;
} }



+ 17
- 0
ShopBundle/Model/Newsletter.php View File

*/ */
protected $users; protected $users;


/**
* @ORM\Column(type="boolean", nullable=true)
*/
protected $isMain;

public function __toString() public function __toString()
{ {
return $this->getTitle() ; return $this->getTitle() ;


return $this; return $this;
} }

public function getIsMain(): ?bool
{
return $this->isMain;
}

public function setIsMain(?bool $isMain): self
{
$this->isMain = $isMain;

return $this;
}
} }

+ 6
- 1
ShopBundle/Resources/public/js/backend/script/default/init-list.js View File

}); });




/* $('.action-confirm').each(function () {
$(this).on('click', function (e) {
return confirm("Êtes vous sur de vouloir effectuer cette action ?");
});
});*/
$('.action-duplicate').each(function () { $('.action-duplicate').each(function () {
$(this).on('click', function (e) { $(this).on('click', function (e) {
return confirm("Press a button!");
return confirm("Êtes vous sur de vouloir effectuer cette action ?");
}); });
}); });
} }

+ 1
- 0
ShopBundle/Resources/translations/lcshop.fr.yaml View File

displaySpecificDay: Disponible un jour spécifique displaySpecificDay: Disponible un jour spécifique
groupUsers: Groupes groupUsers: Groupes
ticketTypesNotification: Catégorie ticket ticketTypesNotification: Catégorie ticket
newsletter: Newsletter


PointSale: PointSale:
code: Code code: Code

+ 81
- 0
ShopBundle/Services/MailjetSMS.php View File

<?php

namespace Lc\ShopBundle\Services;

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class MailjetSMS
{
protected $client;
protected $parameterBag;
protected $mailUtils ;
protected $utils ;

public function __construct(HttpClientInterface $client, ParameterBagInterface $parameterBag, UtilsManager $utilsManager)
{
$this->client = $client;
$this->parameterBag = $parameterBag;
$this->mailUtils = $utilsManager->getMailUtils() ;
$this->utils = $utilsManager->getUtils() ;
}

public function send($user, $message)
{

if($user) {
$phone = $this->utils->formatPhoneNumber($user->getPhone()) ;

if($this->parameterBag->get('mailjet.dev.redirect.active') == 1) {
$this->mailUtils->send([
MailUtils::SUBJECT => 'Notification par SMS à '.$phone,
MailUtils::TO_EMAIL => $user->getEmail(),
MailUtils::CONTENT_TEMPLATE => 'mail/notification',
MailUtils::CONTENT_DATA => [
'message' => $message
],
]);

return true ;
}
else {
$token = $this->parameterBag->get('mailjet.sms.token');
$from = $this->parameterBag->get('mailjet.sms.from');

if ($token && strlen($token) > 0) {
$response = $this->client->request(
'POST',
'https://api.mailjet.com/v4/sms-send',
[
'headers' => [
'Authorization' => 'Bearer ' . $token,
],
'json' => [
'From' => $from,
'To' => $phone,
'Text' => $message,
]
]
);

$statusCode = $response->getStatusCode();

if ($statusCode == 200) {
$content = $response->getContent();
$content = $response->toArray();
return $content;
} else {
// log
}
}
else {
throw new \ErrorException('Le token SMS Mailjet n\'est pas défini.');
}
}
}

return false;
}

}

+ 104
- 123
ShopBundle/Services/UserUtils.php View File



class UserUtils class UserUtils
{ {
protected $parameterBag;
protected $em;
protected $utils;
protected $requestStack;
protected $visitorRepository;
protected $merchantUtils;
protected $cookieChecker;
protected $visitor;

public function __construct(ParameterBagInterface $parameterBag, EntityManagerInterface $em, Utils $utils,
RequestStack $requestStack, MerchantUtilsInterface $merchantUtils, CookieChecker $cookieChecker,
Security $security)
{
$this->em = $em;
$this->parameterBag = $parameterBag;
$this->utils = $utils;
$this->requestStack = $requestStack;
$this->visitorRepository = $this->em->getRepository($this->em->getClassMetadata(VisitorInterface::class)->getName());
$this->merchantUtils = $merchantUtils;
$this->cookieChecker = $cookieChecker;
$this->security = $security;
}

public function getCookieNameVisitor()
{
return $this->parameterBag->get('app.cookie_name_visitor');
}

public function cryptCookie($data)
{
return base64_encode($data);
}

public function decryptCookie($data)
{
return base64_decode($data);
}

public function setCookieVisitor($response, $cookie)
{
$response->headers->setCookie(Cookie::create($this->getCookieNameVisitor(), $this->cryptCookie($cookie), new \DateTime('+2 months'), '/', $this->utils->getCookieDomain()));
}

public function updateVisitorCookie($response)
{
$response->headers->setCookie(Cookie::create($this->getCookieNameVisitor(), $this->cryptCookie($this->getVisitorCurrent()->getCookie()), new \DateTime('+2 months'), '/', $this->utils->getCookieDomain()));

}

public function getVisitor($cookie)
{
if (!isset($this->visitor[$cookie])) {
$this->visitor[$cookie] = $this->visitorRepository->findOneBy(['cookie' => $cookie]);
protected $parameterBag;
protected $em;
protected $utils;
protected $requestStack;
protected $visitorRepository;
protected $merchantUtils;
protected $cookieChecker;
protected $visitor;

public function __construct(ParameterBagInterface $parameterBag, EntityManagerInterface $em, Utils $utils,
RequestStack $requestStack, MerchantUtilsInterface $merchantUtils, CookieChecker $cookieChecker,
Security $security)
{
$this->em = $em;
$this->parameterBag = $parameterBag;
$this->utils = $utils;
$this->requestStack = $requestStack;
$this->visitorRepository = $this->em->getRepository($this->em->getClassMetadata(VisitorInterface::class)->getName());
$this->merchantUtils = $merchantUtils;
$this->cookieChecker = $cookieChecker;
$this->security = $security;
} }
return $this->visitor[$cookie];
}

public function getVisitorCurrent()
{
$cookie = $this->requestStack->getCurrentRequest()->cookies->get($this->getCookieNameVisitor());
return $this->getVisitor($cookie);
}

public function addVisitor($cookie, $ip)
{
$classVisitor = $this->em->getClassMetadata(VisitorInterface::class)->getName();
$visitor = new $classVisitor;

$visitor->setCookie($cookie);
$visitor->setIp($ip);
$visitor->setTotalVisit(1);
$visitor->setLastAccess(new \DateTime());

$this->em->persist($visitor);
$this->em->flush();
}

public function updateVisitor($visitor)
{
$totalVisit = $visitor->getTotalVisit() + 1;
$visitor->setTotalVisit($totalVisit);
$visitor->setLastAccess(new \DateTime());

$this->em->persist($visitor);
$this->em->flush();
}

public function setNewsletter($user, $subscribeNewsletter)
{
$currentMerchant = $this->merchantUtils->getMerchantCurrent();
$newsletters = $currentMerchant->getNewsletters();

if($newsletters && count($newsletters) > 0) {
if ($subscribeNewsletter) {
$user->addNewsletter($newsletters[0]);
}
else {
$user->removeNewsletter($newsletters[0]);
}

public function getCookieNameVisitor()
{
return $this->parameterBag->get('app.cookie_name_visitor');
}

public function cryptCookie($data)
{
return base64_encode($data);
}

public function decryptCookie($data)
{
return base64_decode($data);
}

public function setCookieVisitor($response, $cookie)
{
$response->headers->setCookie(Cookie::create($this->getCookieNameVisitor(), $this->cryptCookie($cookie), new \DateTime('+2 months'), '/', $this->utils->getCookieDomain()));
}

public function updateVisitorCookie($response)
{
$response->headers->setCookie(Cookie::create($this->getCookieNameVisitor(), $this->cryptCookie($this->getVisitorCurrent()->getCookie()), new \DateTime('+2 months'), '/', $this->utils->getCookieDomain()));

}

public function getVisitor($cookie)
{
if (!isset($this->visitor[$cookie])) {
$this->visitor[$cookie] = $this->visitorRepository->findOneBy(['cookie' => $cookie]);
}
return $this->visitor[$cookie];
}

public function getVisitorCurrent()
{
$cookie = $this->requestStack->getCurrentRequest()->cookies->get($this->getCookieNameVisitor());
return $this->getVisitor($cookie);
}

public function addVisitor($cookie, $ip)
{
$classVisitor = $this->em->getClassMetadata(VisitorInterface::class)->getName();
$visitor = new $classVisitor;

$visitor->setCookie($cookie);
$visitor->setIp($ip);
$visitor->setTotalVisit(1);
$visitor->setLastAccess(new \DateTime());

$this->em->persist($visitor);
$this->em->flush();
}

public function updateVisitor($visitor)
{
$totalVisit = $visitor->getTotalVisit() + 1;
$visitor->setTotalVisit($totalVisit);
$visitor->setLastAccess(new \DateTime());

$this->em->persist($visitor);
$this->em->flush();
} }


$this->em->persist($user);
$this->em->flush();
}

/*public function setNewsletter($user, $newsletter, $subscribeNewsletter)
{
$currentMerchant = $this->merchantUtils->getMerchantCurrent() ;
$newsletters = $currentMerchant->getNewsletters() ;

foreach($newsletters as $newsletterMerchant) {
if($newsletterMerchant == $newsletter) {
if($subscribeNewsletter) {
$user->addNewsletter($newsletter) ;
}
else {
$user->removeNewsletter($newsletter) ;
}
public function setNewsletter($user, $newsletter, $subscribeNewsletter)
{
$currentMerchant = $this->merchantUtils->getMerchantCurrent();
$newsletters = $currentMerchant->getNewsletters();

foreach ($newsletters as $newsletterMerchant) {
if ($newsletterMerchant->getId() == $newsletter->getId()) {
if ($subscribeNewsletter) {
$user->addNewsletter($newsletter);
} else {
$user->removeNewsletter($newsletter);
}
}
} }
}


$this->em->persist($user) ;
$this->em->flush() ;
}*/
$this->em->persist($user);
$this->em->flush();
}


public function isSubscribedToNewsletter($user, $newsletter)
{
return $user->getNewsletters()->contains($newsletter);
}
public function isSubscribedToNewsletter($user, $newsletter)
{
return $user->getNewsletters()->contains($newsletter);
}


} }

+ 13
- 0
ShopBundle/Services/Utils.php View File

return round((($price * 100)) / 100, $precision); return round((($price * 100)) / 100, $precision);
} }


public function formatPhoneNumber($phone)
{
$phone = preg_replace('`[^0-9]`', '', $phone);
if(strlen($phone) == 10) {
$phone = '+33'.substr($phone, 1, 9) ;
}
elseif(strlen($phone) == 11 && substr($phone, 0, 2) == '33') {
$phone = '+'.$phone ;
}

return $phone ;
}



} }

+ 2
- 1
ShopBundle/Twig/FrontendTwigExtension.php View File



namespace Lc\ShopBundle\Twig; namespace Lc\ShopBundle\Twig;


use App\Services\NotificationUtils;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Lc\ShopBundle\Context\MerchantInterface; use Lc\ShopBundle\Context\MerchantInterface;
use Lc\ShopBundle\Context\MerchantUtilsInterface; use Lc\ShopBundle\Context\MerchantUtilsInterface;
new TwigFunction('get_merchants', [$this, 'getMerchants']), new TwigFunction('get_merchants', [$this, 'getMerchants']),
new TwigFunction('get_file_manager_folder', [$this, 'getFileManagerFolder']), new TwigFunction('get_file_manager_folder', [$this, 'getFileManagerFolder']),
new TwigFunction('lc_format_price', [$this, 'formatPrice']), new TwigFunction('lc_format_price', [$this, 'formatPrice']),
new TwigFunction('get_form_manage_notifications', [$this, 'getFormManageNotifications']),
); );
} }


{ {
return $this->merchantRepository->findAll(); return $this->merchantRepository->findAll();
} }

} }

Loading…
Cancel
Save