1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace hamburgscleanest\GuzzleAdvancedThrottle\Cache\Adapters; |
4
|
|
|
|
5
|
|
|
use DateTime; |
6
|
|
|
use hamburgscleanest\GuzzleAdvancedThrottle\Cache\Interfaces\StorageInterface; |
7
|
|
|
use hamburgscleanest\GuzzleAdvancedThrottle\RequestInfo; |
8
|
|
|
use Illuminate\Cache\CacheManager; |
9
|
|
|
use Illuminate\Container\Container; |
10
|
|
|
use Illuminate\Filesystem\Filesystem; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class LaravelAdapter |
14
|
|
|
* @package hamburgscleanest\GuzzleAdvancedThrottle\Cache\Adapters |
15
|
|
|
*/ |
16
|
|
|
class LaravelAdapter implements StorageInterface |
17
|
|
|
{ |
18
|
|
|
|
19
|
|
|
/** @var CacheManager */ |
20
|
|
|
private $_cacheManager; |
21
|
|
|
|
22
|
1 |
|
public function __construct() |
23
|
|
|
{ |
24
|
1 |
|
$container = new Container(); |
25
|
|
|
|
26
|
|
|
// TODO: Set from outside.. |
27
|
1 |
|
$container['config'] = [ |
28
|
|
|
'cache.default' => 'file', |
29
|
|
|
'cache.stores.file' => [ |
30
|
|
|
'driver' => 'file', |
31
|
|
|
'path' => __DIR__ . '/cache' |
32
|
|
|
] |
33
|
|
|
]; |
34
|
1 |
|
$container['files'] = new Filesystem(); // TODO: Remove when config extracted.. |
35
|
|
|
|
36
|
1 |
|
$this->_cacheManager = new CacheManager($container); |
37
|
1 |
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param string $host |
41
|
|
|
* @param string $key |
42
|
|
|
* @param int $requestCount |
43
|
|
|
* @param DateTime $expiresAt |
44
|
|
|
* @param int $remainingSeconds |
45
|
|
|
*/ |
46
|
1 |
|
public function save(string $host, string $key, int $requestCount, DateTime $expiresAt, int $remainingSeconds) : void |
47
|
|
|
{ |
48
|
1 |
|
$this->_cacheManager->put( |
49
|
1 |
|
$this->_buildKey($host, $key), |
50
|
1 |
|
RequestInfo::create($requestCount, $expiresAt->getTimestamp(), $remainingSeconds), |
51
|
1 |
|
$remainingSeconds |
52
|
|
|
); |
53
|
1 |
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param string $host |
57
|
|
|
* @param string $key |
58
|
|
|
* @return string |
59
|
|
|
*/ |
60
|
1 |
|
private function _buildKey(string $host, string $key) : string |
61
|
|
|
{ |
62
|
1 |
|
return $host . '.' . $key; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param string $host |
67
|
|
|
* @param string $key |
68
|
|
|
* @return RequestInfo|null |
69
|
|
|
*/ |
70
|
1 |
|
public function get(string $host, string $key) : ? RequestInfo |
71
|
|
|
{ |
72
|
|
|
/** @noinspection PhpIncompatibleReturnTypeInspection */ |
73
|
1 |
|
return $this->_cacheManager->get($this->_buildKey($host, $key)); |
74
|
|
|
} |
75
|
|
|
} |