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\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, CacheInterface $cache = null) |
31
|
|
|
{ |
32
|
1 |
|
$this->urls = $urls; |
33
|
1 |
|
$this->cache = $cache instanceof CacheInterface ? $cache : new ArrayCache(); |
34
|
1 |
|
} |
35
|
|
|
|
36
|
1 |
|
public function __invoke(ServerRequestInterface $request, callable $next) |
37
|
|
|
{ |
38
|
1 |
|
if ($request->getMethod() !== 'GET') { |
39
|
|
|
return resolve($next($request)); |
40
|
|
|
} |
41
|
|
|
|
42
|
1 |
|
$uri = $request->getUri()->getPath(); |
43
|
1 |
|
if (!in_array($uri, $this->urls, true)) { |
44
|
|
|
return resolve($next($request)); |
45
|
|
|
} |
46
|
|
|
|
47
|
1 |
|
$key = $uri; |
48
|
|
|
|
49
|
1 |
|
return $this->cache->get($key)->then(function ($json) { |
50
|
1 |
|
$cachedResponse = json_decode($json); |
51
|
|
|
|
52
|
1 |
|
return new Response($cachedResponse->code, [], stream_for($cachedResponse->body)); |
53
|
|
|
}, function () use ($next, $request, $key) { |
54
|
1 |
|
return resolve($next($request))->then(function (ResponseInterface $response) use ($key) { |
55
|
1 |
|
if (!($response->getBody() instanceof HttpBodyStream)) { |
56
|
1 |
|
$body = (string)$response->getBody(); |
57
|
1 |
|
$cachedResponse = json_encode([ |
58
|
1 |
|
'body' => $body, |
59
|
1 |
|
'code' => $response->getStatusCode(), |
60
|
|
|
]); |
61
|
1 |
|
$this->cache->set($key, $cachedResponse); |
62
|
1 |
|
$response = $response->withBody(stream_for($body)); |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
return $response; |
66
|
1 |
|
}); |
67
|
|
|
}); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g.
excluded_paths: ["lib/*"]
, you can move it to the dependency path list as follows:For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths