-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCacheMiddleware.php
More file actions
71 lines (56 loc) · 2.11 KB
/
CacheMiddleware.php
File metadata and controls
71 lines (56 loc) · 2.11 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
<?php
declare(strict_types=1);
namespace Saloon\CachePlugin\Http\Middleware;
use Saloon\Http\Response;
use Saloon\Enums\PipeOrder;
use Saloon\Http\PendingRequest;
use Saloon\Contracts\FakeResponse;
use Saloon\Contracts\RequestMiddleware;
use Saloon\CachePlugin\Contracts\Driver;
use Saloon\CachePlugin\Data\CachedResponse;
use Saloon\CachePlugin\Helpers\CacheKeyHelper;
class CacheMiddleware implements RequestMiddleware
{
/**
* Constructor
*/
public function __construct(
protected Driver $driver,
protected ?string $cacheKey,
protected bool $invalidate = false,
) {
//
}
/**
* Handle the middleware
*
* @throws \JsonException
*/
public function __invoke(PendingRequest $pendingRequest): ?FakeResponse
{
$driver = $this->driver;
$cacheKey = hash('sha256', $this->cacheKey ?? CacheKeyHelper::create($pendingRequest));
$cachedResponse = $driver->get($cacheKey);
// If we have found a cached response on the driver, then we will
// check if the cached response hasn't expired.
if ($cachedResponse instanceof CachedResponse) {
// If the cached response is still active, we will return
// the SimulatedResponsePayload here.
if ($this->invalidate === false && $cachedResponse->hasNotExpired()) {
$pendingRequest->middleware()->onResponse(fn (Response $response) => $response->setCached(true), order: PipeOrder::FIRST);
return $cachedResponse->getFakeResponse();
}
// However if it has expired we will delete it and register
// the CacheRecorderMiddleware.
$driver->delete($cacheKey);
}
// Register the CacheRecorderMiddleware which will record the response
// and store it on the cache driver for next time. We'll also use
// the prepend option, so it runs first.
$pendingRequest->middleware()->onResponse(
callable: new CacheRecorderMiddleware($driver, $cacheKey),
order: PipeOrder::FIRST
);
return null;
}
}