|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* @copyright Copyright (c) Flipbox Digital Limited |
|
5
|
|
|
* @license https://github.com/flipbox/relay-simplecache/blob/master/LICENSE |
|
6
|
|
|
* @link https://github.com/flipbox/relay-simplecache |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Flipbox\Relay\Middleware; |
|
10
|
|
|
|
|
11
|
|
|
use Flipbox\Relay\Exceptions\InvalidSimpleCacheException; |
|
12
|
|
|
use Psr\Http\Message\RequestInterface; |
|
13
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
14
|
|
|
use Psr\SimpleCache\CacheInterface; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @author Flipbox Factory <[email protected]> |
|
18
|
|
|
* @since 1.1.0 |
|
19
|
|
|
*/ |
|
20
|
|
|
abstract class AbstractSimpleCache extends AbstractMiddleware |
|
21
|
|
|
{ |
|
22
|
|
|
/** |
|
23
|
|
|
* @var CacheInterface |
|
24
|
|
|
*/ |
|
25
|
|
|
public $cache; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @var string |
|
29
|
|
|
*/ |
|
30
|
|
|
public $key; |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* @inheritdoc |
|
34
|
|
|
*/ |
|
35
|
|
|
public function init() |
|
36
|
|
|
{ |
|
37
|
|
|
parent::init(); |
|
38
|
|
|
|
|
39
|
|
|
if (!$this->cache instanceof CacheInterface) { |
|
40
|
|
|
throw new InvalidSimpleCacheException( |
|
41
|
|
|
sprintf( |
|
42
|
|
|
"The class '%s' requires a cache instance of '%s', '%s' given.", |
|
43
|
|
|
get_class($this), |
|
44
|
|
|
CacheInterface::class, |
|
45
|
|
|
get_class($this->cache) |
|
46
|
|
|
) |
|
47
|
|
|
); |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* Returns the id used to cache a request. |
|
53
|
|
|
* |
|
54
|
|
|
* @param RequestInterface $request |
|
55
|
|
|
* |
|
56
|
|
|
* @return string |
|
57
|
|
|
*/ |
|
58
|
|
|
protected function getCacheKey(RequestInterface $request): string |
|
59
|
|
|
{ |
|
60
|
|
|
if ($this->key === null) { |
|
61
|
|
|
$this->key = $request->getMethod() . md5((string)$request->getUri()); |
|
62
|
|
|
} |
|
63
|
|
|
return (string)$this->key; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* @param ResponseInterface $response |
|
68
|
|
|
* @return bool |
|
69
|
|
|
*/ |
|
70
|
|
|
protected function isResponseSuccessful(ResponseInterface $response): bool |
|
71
|
|
|
{ |
|
72
|
|
|
if ($response->getStatusCode() >= 200 && |
|
73
|
|
|
$response->getStatusCode() < 300 |
|
74
|
|
|
) { |
|
75
|
|
|
return true; |
|
76
|
|
|
} |
|
77
|
|
|
$this->warning( |
|
78
|
|
|
"API request was not successful", |
|
79
|
|
|
[ |
|
80
|
|
|
'code' => $response->getStatusCode(), |
|
81
|
|
|
'reason' => $response->getReasonPhrase() |
|
82
|
|
|
] |
|
83
|
|
|
); |
|
84
|
|
|
return false; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|