<?php
namespace App\EventSubscriber;
use App\Blog;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Contracts\Cache\CacheInterface;
class ContentRefreshSubscriber implements EventSubscriberInterface
{
public function __construct(private CacheInterface $cache, private Blog $blog)
{
}
public function onKernelRequest(RequestEvent $event): void
{
// Refresh content if a special query parameter is given
$request = $event->getRequest();
if ($request->query->has('refresh')) {
$this->refresh();
}
}
public function onKernelTerminate(TerminateEvent $event): void
{
// Periodically reload site content after responses are sent
$lastRefresh = $this->cache->get('lastContentRefresh', function () {
return 0;
});
if ($lastRefresh < strtotime('-5 minutes')) {
$this->refresh();
}
}
private function refresh(): void
{
// Update the last refresh time now to minimize cache stampede
$this->cache->get('lastContentRefresh', function () {
return time();
}, INF);
$this->blog->bustCache();
}
public static function getSubscribedEvents(): array
{
return [
'kernel.request' => 'onKernelRequest',
'kernel.terminate' => 'onKernelTerminate',
];
}
}