|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace hamburgscleanest\GuzzleAdvancedThrottle\Cache\Adapters; |
|
4
|
|
|
|
|
5
|
|
|
use GuzzleHttp\Psr7\Response; |
|
6
|
|
|
use hamburgscleanest\GuzzleAdvancedThrottle\Cache\Interfaces\StorageInterface; |
|
7
|
|
|
use hamburgscleanest\GuzzleAdvancedThrottle\Helpers\RequestHelper; |
|
8
|
|
|
use Psr\Http\Message\RequestInterface; |
|
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
10
|
|
|
|
|
11
|
|
|
abstract class BaseAdapter implements StorageInterface |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var int */ |
|
14
|
|
|
protected const DEFAULT_TTL = 300; |
|
15
|
|
|
/** @var string */ |
|
16
|
|
|
protected const STORAGE_KEY = 'requests'; |
|
17
|
|
|
|
|
18
|
|
|
/** Time To Live in minutes */ |
|
19
|
|
|
protected int $_ttl = self::DEFAULT_TTL; |
|
20
|
|
|
/** false -> empty responses won't be cached. */ |
|
21
|
|
|
protected bool $_allowEmptyValues = true; |
|
22
|
|
|
|
|
23
|
16 |
|
final public function saveResponse(RequestInterface $request, ResponseInterface $response): void |
|
24
|
|
|
{ |
|
25
|
16 |
|
if (!$this->_allowEmptyValues && $response->getBody()->getSize() === 0) { |
|
26
|
2 |
|
return; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
14 |
|
[$host, $path] = RequestHelper::getHostAndPath($request); |
|
30
|
|
|
|
|
31
|
14 |
|
$this->_saveResponse($response, $host, $path, RequestHelper::getStorageKey($request)); |
|
32
|
14 |
|
} |
|
33
|
|
|
|
|
34
|
|
|
abstract protected function _saveResponse(ResponseInterface $response, string $host, string $path, string $key): void; |
|
35
|
|
|
|
|
36
|
21 |
|
final public function getResponse(RequestInterface $request): ?ResponseInterface |
|
37
|
|
|
{ |
|
38
|
21 |
|
[$host, $path] = RequestHelper::getHostAndPath($request); |
|
39
|
|
|
|
|
40
|
21 |
|
return $this->_getResponse($host, $path, RequestHelper::getStorageKey($request)); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
abstract protected function _getResponse(string $host, string $path, string $key): ?Response; |
|
44
|
|
|
} |
|
45
|
|
|
|