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 React\Http\Response; |
11
|
|
|
use function React\Promise\resolve; |
|
|
|
|
12
|
|
|
use function RingCentral\Psr7\stream_for; |
|
|
|
|
13
|
|
|
|
14
|
|
|
final class ResponseCacheMiddleware |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var array |
18
|
|
|
*/ |
19
|
|
|
private $urls = []; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var CacheInterface |
23
|
|
|
*/ |
24
|
|
|
private $cache; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param array $urls |
28
|
|
|
* @param CacheInterface $cache |
29
|
|
|
*/ |
30
|
1 |
|
public function __construct(array $urls, array $headers = [], CacheInterface $cache = null) |
31
|
|
|
{ |
32
|
1 |
|
$this->urls = $urls; |
33
|
1 |
|
$this->headers = $headers; |
|
|
|
|
34
|
1 |
|
$this->cache = $cache instanceof CacheInterface ? $cache : new ArrayCache(); |
35
|
1 |
|
} |
36
|
|
|
|
37
|
1 |
|
public function __invoke(ServerRequestInterface $request, callable $next) |
38
|
|
|
{ |
39
|
1 |
|
if ($request->getMethod() !== 'GET') { |
40
|
|
|
return resolve($next($request)); |
41
|
|
|
} |
42
|
|
|
|
43
|
1 |
|
$uri = $request->getUri()->getPath(); |
44
|
1 |
|
if (!in_array($uri, $this->urls, true)) { |
45
|
|
|
return resolve($next($request)); |
46
|
|
|
} |
47
|
|
|
|
48
|
1 |
|
$key = $uri; |
49
|
|
|
|
50
|
1 |
|
return $this->cache->get($key)->then(function ($json) { |
51
|
1 |
|
$cachedResponse = json_decode($json); |
52
|
|
|
|
53
|
1 |
|
return new Response($cachedResponse->code, (array)$cachedResponse->headers, stream_for($cachedResponse->body)); |
54
|
|
|
}, function () use ($next, $request, $key) { |
55
|
1 |
|
return resolve($next($request))->then(function (ResponseInterface $response) use ($key) { |
56
|
1 |
|
if ($response->getBody() instanceof HttpBodyStream) { |
57
|
1 |
|
return $response; |
58
|
|
|
} |
59
|
|
|
|
60
|
1 |
|
$body = (string)$response->getBody(); |
61
|
1 |
|
$headers = []; |
62
|
1 |
|
foreach ($this->headers as $header) { |
63
|
1 |
|
if (!$response->hasHeader($header)) { |
64
|
|
|
continue; |
65
|
|
|
} |
66
|
|
|
|
67
|
1 |
|
$headers[$header] = $response->getHeaderLine($header); |
68
|
|
|
} |
69
|
1 |
|
$cachedResponse = json_encode([ |
70
|
1 |
|
'body' => $body, |
71
|
1 |
|
'headers' => $headers, |
72
|
1 |
|
'code' => $response->getStatusCode(), |
73
|
|
|
]); |
74
|
1 |
|
$this->cache->set($key, $cachedResponse); |
75
|
|
|
|
76
|
1 |
|
return $response->withBody(stream_for($body)); |
77
|
1 |
|
}); |
78
|
1 |
|
}); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|