-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathEtagCachePlugin.php
More file actions
78 lines (68 loc) · 2.46 KB
/
EtagCachePlugin.php
File metadata and controls
78 lines (68 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace Http\Client\Common\Plugin;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamFactoryInterface;
/**
* Allow for caching only ETag-backed responses with a PSR-6 compatible caching engine.
*
* Cached responses are always revalidated with the origin before their cached body is returned.
*/
final class EtagCachePlugin extends AbstractCachePlugin
{
/**
* This method will setup the cachePlugin in client cache mode. When using the client cache mode the plugin will
* cache responses with `private` cache directive.
*
* @param mixed[] $config For all possible config options see the constructor docs
*
* @return EtagCachePlugin
*/
public static function clientCache(CacheItemPoolInterface $pool, StreamFactoryInterface $streamFactory, array $config = [])
{
return new self($pool, $streamFactory, self::prepareClientCacheConfig($config));
}
/**
* This method will setup the cachePlugin in server cache mode. This is the default caching behavior it refuses to
* cache responses with the `private`or `no-cache` directives.
*
* @param mixed[] $config For all possible config options see the constructor docs
*
* @return EtagCachePlugin
*/
public static function serverCache(CacheItemPoolInterface $pool, StreamFactoryInterface $streamFactory, array $config = [])
{
return new self($pool, $streamFactory, $config);
}
/**
* @return int
*/
protected static function calculateResponseExpiresAt(?int $maxAge)
{
return 0;
}
protected function isCacheable(ResponseInterface $response)
{
return parent::isCacheable($response) && self::responseHasETag($response);
}
/**
* @param mixed[] $data
*/
protected static function shouldUseCachedResponse(array $data): bool
{
return false;
}
protected static function withCacheValidationHeaders(RequestInterface $request, CacheItemInterface $cacheItem): RequestInterface
{
if ($etag = self::getETag($cacheItem)) {
$request = $request->withHeader('If-None-Match', $etag);
}
return $request;
}
protected static function canUseCacheItemForNotModifiedResponse(CacheItemInterface $cacheItem): bool
{
return $cacheItem->isHit() && null !== self::getETag($cacheItem);
}
}