83 lines
2.7KB

  1. <?php
  2. namespace Lc\ShopBundle\Services ;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Symfony\Component\HttpFoundation\Cookie ;
  5. use Lc\ShopBundle\Context\VisitorInterface;
  6. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  7. use Symfony\Component\HttpFoundation\RequestStack;
  8. class UserUtils
  9. {
  10. protected $parameterBag ;
  11. protected $em ;
  12. protected $utils ;
  13. protected $requestStack ;
  14. protected $visitorRepository ;
  15. public function __construct(ParameterBagInterface $parameterBag, EntityManagerInterface $em, Utils $utils, RequestStack $requestStack)
  16. {
  17. $this->em = $em ;
  18. $this->parameterBag = $parameterBag ;
  19. $this->utils = $utils ;
  20. $this->requestStack = $requestStack ;
  21. $this->visitorRepository = $this->em->getRepository($this->em->getClassMetadata(VisitorInterface::class)->getName()) ;
  22. }
  23. public function getCookieNameVisitor()
  24. {
  25. return $this->parameterBag->get('app.cookie_name_visitor') ;
  26. }
  27. public function cryptCookie($data)
  28. {
  29. return base64_encode($data);
  30. }
  31. public function decryptCookie($data)
  32. {
  33. return base64_decode($data);
  34. }
  35. public function setCookieVisitor($response, $cookie)
  36. {
  37. $response->headers->setCookie(Cookie::create($this->getCookieNameVisitor(), $this->cryptCookie($cookie), 0, '/', $this->utils->getCookieDomain()));
  38. }
  39. public function getVisitor($cookie)
  40. {
  41. return $this->visitorRepository->findOneBy(['cookie' => $cookie]) ;
  42. }
  43. public function getVisitorCurrent()
  44. {
  45. $cookie = $this->requestStack->getCurrentRequest()->cookies->get($this->getCookieNameVisitor()) ;
  46. return $this->getVisitor($cookie) ;
  47. }
  48. public function addVisitor($cookie, $ip)
  49. {
  50. $classVisitor = $this->em->getClassMetadata(VisitorInterface::class)->getName() ;
  51. $visitor = new $classVisitor ;
  52. $visitor->setCookie($cookie) ;
  53. $visitor->setIp($ip) ;
  54. $visitor->setTotalVisit(1) ;
  55. $visitor->setLastAccess(new \DateTime()) ;
  56. $this->em->persist($visitor);
  57. $this->em->flush() ;
  58. }
  59. public function updateVisitor($visitor)
  60. {
  61. $totalVisit = $visitor->getTotalVisit() + 1 ;
  62. $visitor->setTotalVisit($totalVisit) ;
  63. $visitor->setLastAccess(new \DateTime()) ;
  64. $this->em->persist($visitor);
  65. $this->em->flush() ;
  66. }
  67. }