<?php
declare(strict_types=1);
namespace Hitso\Bundle\ContentBundle\EventListener;
use Hitso\Bundle\ContentBundle\Services\ElasticSearch\ElasticSearchVisitManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class ContentHitSubscriber implements EventSubscriberInterface
{
public function onKernelResponse(FilterResponseEvent $event): void
{
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
if (!$this->isHittable($request)) {
return;
}
ElasticSearchVisitManager::hit($this->getSlug($request));
}
private function isHittable(Request $request): bool
{
if (!$request->hasSession()) {
return false;
}
$hittable = false;
$attr = $request->attributes;
$session = $request->getSession();
$contentSeen = $session->get('contentSeen', []);
$slug = $this->getSlug($request);
if ($slug && $attr->has('_hittable') && !isset($contentSeen[$slug])) {
$contentSeen[$slug] = true;
$session->set('contentSeen', $contentSeen);
$hittable = true;
}
return $hittable;
}
private function getSlug(Request $request): ?string
{
if (!$slug = $request->attributes->get('slug')) {
return null;
}
return substr(trim((string) $slug), 0, 200);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::RESPONSE => [['onKernelResponse', 1]],
];
}
}