<?php
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;
use Predis\Client as RedisClient;
class TwigGlobalSubscriber implements EventSubscriberInterface
{
private Environment $twig;
private RedisClient $redis;
private string $recaptchaSiteKey;
public function __construct(Environment $twig, RedisClient $redis, string $recaptchaSiteKey)
{
$this->twig = $twig;
$this->redis = $redis;
$this->recaptchaSiteKey = $recaptchaSiteKey;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 50],
];
}
public function onKernelRequest(RequestEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$this->twig->addGlobal('recaptcha_site_key', $this->recaptchaSiteKey);
$historyRaw = $this->redis->lrange('chat_messages', 0, 19);
$history = array_reverse(array_map(fn($item) => json_decode($item, true), $historyRaw));
$this->twig->addGlobal('chat_history', $history);
}
}