From 1cd1da2f1558ddee53fef8c0a78c27dc947c8e8e Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Thu, 23 Apr 2020 22:33:48 +0200 Subject: [PATCH] Add possibility to write cache on terminate --- src/Psr6Store.php | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/Psr6Store.php b/src/Psr6Store.php index 8b0bf2b..a2f8bab 100644 --- a/src/Psr6Store.php +++ b/src/Psr6Store.php @@ -24,6 +24,7 @@ use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\TerminableInterface; use Symfony\Component\Lock\BlockingStoreInterface; use Symfony\Component\Lock\Exception\LockReleasingException; use Symfony\Component\Lock\Factory; @@ -43,7 +44,7 @@ * * @author Yanick Witschi */ -class Psr6Store implements Psr6StoreInterface, ClearableInterface +class Psr6Store implements Psr6StoreInterface, ClearableInterface, TerminableInterface { const NON_VARYING_KEY = 'non-varying'; const COUNTER_KEY = 'write-operations-counter'; @@ -90,6 +91,9 @@ public function __construct(array $options = []) $resolver->setDefault('generate_content_digests', true) ->setAllowedTypes('generate_content_digests', 'boolean'); + $resolver->setDefault('write_on_terminate', false) + ->setAllowedTypes('write_on_terminate', 'boolean'); + $resolver->setDefault('cache', function (Options $options) { if (!isset($options['cache_directory'])) { throw new MissingOptionsException('The cache_directory option is required unless you set the cache explicitly'); @@ -165,6 +169,31 @@ public function lookup(Request $request) return null; } + public function write(Request $request, Response $response) + { + if (null === $response->getMaxAge()) { + throw new \InvalidArgumentException('HttpCache should not forward any response without any cache expiration time to the store.'); + } + + // Add a debug header + $response->headers->set(self::CACHE_DEBUG_HEADER, $request->getUri()); + + if (!$this->options['write_on_terminate']) { + $this->doWrite($request, $response); + } + } + + public function terminate(Request $request, Response $response) + { + if (!$this->options['write_on_terminate']) { + return; + } + + if ($response->headers->has(self::CACHE_DEBUG_HEADER)) { + $this->doWrite($request, $response); + } + } + /** * Writes a cache entry to the store for the given Request and Response. * @@ -176,7 +205,7 @@ public function lookup(Request $request) * * @return string The key under which the response is stored */ - public function write(Request $request, Response $response) + protected function doWrite(Request $request, Response $response) { if (null === $response->getMaxAge()) { throw new \InvalidArgumentException('HttpCache should not forward any response without any cache expiration time to the store.');