|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace WyriHaximus\React\Http\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
7
|
|
|
use React\Cache\ArrayCache; |
|
8
|
|
|
use React\Cache\CacheInterface; |
|
9
|
|
|
use React\Http\Io\HttpBodyStream; |
|
10
|
|
|
use function React\Promise\resolve; |
|
11
|
|
|
use function RingCentral\Psr7\stream_for; |
|
12
|
|
|
|
|
13
|
|
|
final class ResponseCacheMiddleware |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @var CacheConfigurationInterface |
|
17
|
|
|
*/ |
|
18
|
|
|
private $cacheConfiguration; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @var CacheInterface |
|
22
|
|
|
*/ |
|
23
|
|
|
private $cache; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @param CacheConfigurationInterface $cacheConfiguration |
|
27
|
|
|
* @param CacheInterface|null $cache |
|
28
|
|
|
*/ |
|
29
|
2 |
|
public function __construct(CacheConfigurationInterface $cacheConfiguration, CacheInterface $cache = null) |
|
30
|
|
|
{ |
|
31
|
2 |
|
$this->cacheConfiguration = $cacheConfiguration; |
|
32
|
2 |
|
$this->cache = $cache instanceof CacheInterface ? $cache : new ArrayCache(); |
|
33
|
2 |
|
} |
|
34
|
|
|
|
|
35
|
2 |
|
public function __invoke(ServerRequestInterface $request, callable $next) |
|
36
|
|
|
{ |
|
37
|
2 |
|
if (!$this->cacheConfiguration->requestIsCacheable($request)) { |
|
38
|
1 |
|
return resolve($next($request)); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
2 |
|
$key = $this->cacheConfiguration->cacheKey($request); |
|
42
|
|
|
|
|
43
|
1 |
|
return $this->cache->get($key)->then(function ($json) { |
|
44
|
1 |
|
return $this->cacheConfiguration->cacheDecode($json); |
|
45
|
|
|
}, function () use ($next, $request, $key) { |
|
46
|
2 |
|
return resolve($next($request))->then(function (ResponseInterface $response) use ($request, $key) { |
|
47
|
2 |
|
if ($response->getBody() instanceof HttpBodyStream) { |
|
48
|
1 |
|
return $response; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
2 |
|
if (!$this->cacheConfiguration->responseIsCacheable($request, $response)) { |
|
52
|
1 |
|
return $response; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
1 |
|
$body = (string)$response->getBody(); |
|
56
|
1 |
|
$encodedResponse = $this->cacheConfiguration->cacheEncode($response->withBody(stream_for($body))); |
|
57
|
1 |
|
$this->cache->set($key, $encodedResponse); |
|
58
|
|
|
|
|
59
|
1 |
|
return $response->withBody(stream_for($body)); |
|
60
|
2 |
|
}); |
|
61
|
2 |
|
}); |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|