attribute-spass/src/Infrastructure/WebApp/Route/CachedResponse.php
2023-10-20 18:04:11 +00:00

48 lines
1.2 KiB
PHP

<?php declare(strict_types=1);
namespace Lubian\AttributeMagic\Infrastructure\WebApp\Route;
use Lubian\AttributeMagic\Infrastructure\Event\AsListener;
use Lubian\AttributeMagic\Infrastructure\WebApp\Request\RequestEvent;
use Symfony\Component\HttpFoundation\Response;
use function apcu_add;
use function apcu_fetch;
use function is_string;
use function md5;
use function serialize;
use function unserialize;
final class CachedResponse
{
#[AsListener(RequestEvent::class, -99)]
public function cachedResponse(RequestEvent $event): void
{
if ($event->request->getMethod() !== 'GET') {
return;
}
$path = md5($event->request->getPathInfo());
$serialized = apcu_fetch($path);
if (! is_string($serialized)) {
return;
}
/** @var Response|null $response */
$response = unserialize($serialized);
$event->response = $response;
$event->stopped = true;
}
#[AsListener(RequestEvent::class, 99)]
public function doCache(RequestEvent $event): void
{
if ($event->response === null) {
return;
}
$path = md5($event->request->getPathInfo());
apcu_add($path, serialize($event->response));
}
}