Skip to content
Snippets Groups Projects
Commit 1712027c authored by Andrew Berry's avatar Andrew Berry
Browse files

Issue #2843420 by deviantintegral, bstan: Support embedding the cache subscriber as a middleware

parent 456de852
Branches 8.x-2.x
Tags 3.0.0
1 merge request!1Issue #2843420: Support embedding the cache subscriber as a middleware
# Guzzle Cache for Drupal
Provides a Drupal cache backend for
[Kevinrob/guzzle-cache-middleware](https://github.com/Kevinrob/guzzle-cache-middleware).
## Automatic caching for all HTTP requests
To enable the caching layer for all HTTP requests automatically, enable the `guzzle_cache_middleware` sub-module.
name: Guzzle Cache Backend Middleware
description: 'Provides a default middleware for the DrupalGuzzleCache.'
package: Caching
type: module
core: 8.x
core_version_requirement: ^8 || ^9
\ No newline at end of file
services:
guzzle_cache.middleware:
class: \Drupal\guzzle_cache\DrupalGuzzleCache
arguments: ['@cache.default']
tags:
- { name: http_client_middleware }
\ No newline at end of file
......@@ -2,9 +2,13 @@
namespace Drupal\guzzle_cache;
use Drupal\Core\Cache\BackendChain;
use Drupal\Core\Cache\MemoryBackend;
use Kevinrob\GuzzleCache\CacheMiddleware;
use Kevinrob\GuzzleCache\Storage\CacheStorageInterface;
use Drupal\Core\Cache\CacheBackendInterface;
use Kevinrob\GuzzleCache\CacheEntry;
use Kevinrob\GuzzleCache\Strategy\PrivateCacheStrategy;
/**
* Provides a Drupal cache backend for the Guzzle caching middleware.
......@@ -48,6 +52,22 @@ class DrupalGuzzleCache implements CacheStorageInterface {
$this->tags = $tags;
}
/**
* Implements invoke() so this class can be used as a middleware.
*
* @return \Kevinrob\GuzzleCache\CacheMiddleware
* The middleware to cache data.
*/
public function __invoke(): CacheMiddleware {
$cache = new BackendChain('default');
$cache->appendBackend(new MemoryBackend());
$cache->appendBackend($this->cache);
$cache = new DrupalGuzzleCache($cache);
$middleware = new CacheMiddleware(new PrivateCacheStrategy($cache));
return $middleware;
}
/**
* Set the cache key prefix.
*
......
......@@ -8,6 +8,7 @@ use Drupal\Tests\UnitTestCase;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Kevinrob\GuzzleCache\CacheEntry;
use Kevinrob\GuzzleCache\CacheMiddleware;
/**
* Tests Guzzle cache integration.
......@@ -120,4 +121,16 @@ class DrupalGuzzleCacheTest extends UnitTestCase {
new DrupalGuzzleCache($backend, $prefix);
}
/**
* Test invoking for a middleware.
*
* @covers ::__invoke
*/
public function testInvoke() {
/** @var \Drupal\Core\Cache\CacheBackendInterface $backend */
$backend = $this->createMock(CacheBackendInterface::class);
$cache = new DrupalGuzzleCache($backend);
$this->assertInstanceOf(CacheMiddleware::class, $cache());
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment