vendor/connectholland/cookie-consent-bundle/Cookie/CookieLogger.php line 31

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of the ConnectHolland CookieConsentBundle package.
  5.  * (c) Connect Holland.
  6.  */
  7. namespace ConnectHolland\CookieConsentBundle\Cookie;
  8. use ConnectHolland\CookieConsentBundle\Entity\CookieConsentLog;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use Doctrine\Persistence\ManagerRegistry;
  11. use Symfony\Component\HttpFoundation\Request;
  12. class CookieLogger
  13. {
  14.     /**
  15.      * @var EntityManagerInterface
  16.      */
  17.     private $entityManager;
  18.     /**
  19.      * @var Request|null
  20.      */
  21.     private $request;
  22.     public function __construct(ManagerRegistry $registry, ?Request $request)
  23.     {
  24.         $this->entityManager $registry->getManagerForClass(CookieConsentLog::class);
  25.         $this->request       $request;
  26.     }
  27.     /**
  28.      * Logs users preferences in database.
  29.      */
  30.     public function log(array $categoriesstring $key): void
  31.     {
  32.         if ($this->request === null) {
  33.             throw new \RuntimeException('No request found');
  34.         }
  35.         $ip $this->anonymizeIp($this->request->getClientIp());
  36.         foreach ($categories as $category => $value) {
  37.             $this->persistCookieConsentLog($category$value$ip$key);
  38.         }
  39.         $this->entityManager->flush();
  40.     }
  41.     protected function persistCookieConsentLog(string $categorystring $valuestring $ipstring $key): void
  42.     {
  43.         $cookieConsentLog = (new CookieConsentLog())
  44.             ->setIpAddress($ip)
  45.             ->setCookieConsentKey($key)
  46.             ->setCookieName($category)
  47.             ->setCookieValue($value)
  48.             ->setTimestamp(new \DateTime());
  49.         $this->entityManager->persist($cookieConsentLog);
  50.     }
  51.     /**
  52.      * GDPR required IP addresses to be saved anonymized.
  53.      */
  54.     protected function anonymizeIp(?string $ip): string
  55.     {
  56.         if ($ip === null) {
  57.             return 'unknown';
  58.         }
  59.         $lastDot strrpos($ip'.') + 1;
  60.         return substr($ip0$lastDot).str_repeat('x'strlen($ip) - $lastDot);
  61.     }
  62. }