-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathCacheRecorderMiddleware.php
More file actions
59 lines (49 loc) · 1.59 KB
/
CacheRecorderMiddleware.php
File metadata and controls
59 lines (49 loc) · 1.59 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
<?php
declare(strict_types=1);
namespace Saloon\CachePlugin\Http\Middleware;
use DateTimeImmutable;
use Saloon\Http\Response;
use Saloon\Data\RecordedResponse;
use Saloon\CachePlugin\Contracts\Driver;
use Saloon\Contracts\ResponseMiddleware;
use Saloon\CachePlugin\Contracts\Cacheable;
use Saloon\CachePlugin\Data\CachedResponse;
use Saloon\CachePlugin\Exceptions\HasCachingException;
class CacheRecorderMiddleware implements ResponseMiddleware
{
/**
* Constructor
*/
public function __construct(
protected Driver $driver,
protected string $cacheKey,
) {
//
}
/**
* Register a response middleware
*
* @throws \Exception
*/
public function __invoke(Response $response): void
{
if ($response->failed()) {
return;
}
$request = $response->getRequest();
$connector = $response->getConnector();
if (! $request instanceof Cacheable && ! $connector instanceof Cacheable) {
throw new HasCachingException(sprintf('Your connector or request must implement %s to use the HasCaching plugin', Cacheable::class));
}
$expiresAt = $request instanceof Cacheable
? $request->resolveCacheExpiry($response)
: $connector->resolveCacheExpiry($response);
if (is_int($expiresAt)) {
$expiresAt = new DateTimeImmutable('+' . $expiresAt .' seconds');
}
$this->driver->set(
key: $this->cacheKey,
cachedResponse: new CachedResponse(RecordedResponse::fromResponse($response), $expiresAt)
);
}
}