src/Hitso/Bundle/CommonBundle/EventListener/GoogleListener.php line 33

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4.  * @author Maciej Kaczmarek <maciej.kaczmarek@autentika.pl>
  5.  */
  6. namespace Hitso\Bundle\CommonBundle\EventListener;
  7. use Doctrine\ORM\EntityManagerInterface;
  8. use Hitso\Bundle\CommonBundle\Entity\VisitLog;
  9. use Hitso\Bundle\CommonBundle\Repository\VisitLogRepository;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  12. use Symfony\Component\HttpKernel\KernelEvents;
  13. class GoogleListener implements EventSubscriberInterface
  14. {
  15.     /**
  16.      * @var EntityManagerInterface
  17.      */
  18.     private $em;
  19.     /**
  20.      * GoogleListener constructor.
  21.      *
  22.      * @param EntityManagerInterface $em
  23.      */
  24.     public function __construct(EntityManagerInterface $em)
  25.     {
  26.         $this->em $em;
  27.     }
  28.     public function onRequest(GetResponseEvent $event)
  29.     {
  30.         if ($event->isMasterRequest()) {
  31.             $request $event->getRequest();
  32.             $agent   $request->headers->get('User-Agent');
  33.             if ($agent && preg_match('/googlebot/i'$agent)) {
  34.                 /** @var VisitLogRepository $visits */
  35.                 $visits $this->em->getRepository(VisitLog::class);
  36.                 $visits->logVisit(VisitLog::TYPE_GOOGLE);
  37.             }
  38.         }
  39.     }
  40.     /**
  41.      * {@inheritdoc}
  42.      */
  43.     public static function getSubscribedEvents()
  44.     {
  45.         return [
  46.             KernelEvents::REQUEST => 'onRequest',
  47.         ];
  48.     }
  49. }