1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace hamburgscleanest\GuzzleAdvancedThrottle; |
4
|
|
|
|
5
|
|
|
use hamburgscleanest\GuzzleAdvancedThrottle\Cache\Adapters\ArrayAdapter; |
6
|
|
|
use hamburgscleanest\GuzzleAdvancedThrottle\Cache\Adapters\LaravelAdapter; |
7
|
|
|
use hamburgscleanest\GuzzleAdvancedThrottle\Cache\Interfaces\StorageInterface; |
8
|
|
|
use hamburgscleanest\GuzzleAdvancedThrottle\Exceptions\UnknownStorageAdapterException; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class RequestLimitRuleset |
12
|
|
|
* @package hamburgscleanest\GuzzleAdvancedThrottle |
13
|
|
|
*/ |
14
|
|
|
class RequestLimitRuleset |
15
|
|
|
{ |
16
|
|
|
|
17
|
|
|
/** @var array */ |
18
|
|
|
private const STORAGE_MAP = [ |
19
|
|
|
'array' => ArrayAdapter::class, |
20
|
|
|
'laravel' => LaravelAdapter::class |
21
|
|
|
]; |
22
|
|
|
|
23
|
|
|
/** @var array */ |
24
|
|
|
private $_rules; |
25
|
|
|
|
26
|
|
|
/** @var StorageInterface */ |
27
|
|
|
private $_storage; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* RequestLimitRuleset constructor. |
31
|
|
|
* @param array $rules |
32
|
|
|
* @param string|null $storageAdapter |
33
|
|
|
* @throws \hamburgscleanest\GuzzleAdvancedThrottle\Exceptions\UnknownStorageAdapterException |
34
|
|
|
*/ |
35
|
3 |
|
public function __construct(array $rules, string $storageAdapter = 'array') |
36
|
|
|
{ |
37
|
3 |
|
$this->_rules = $rules; |
38
|
3 |
|
$this->_setStorageAdapter($storageAdapter); |
39
|
2 |
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param string $adapterName |
43
|
|
|
* @throws \hamburgscleanest\GuzzleAdvancedThrottle\Exceptions\UnknownStorageAdapterException |
44
|
|
|
*/ |
45
|
3 |
|
private function _setStorageAdapter(string $adapterName) : void |
46
|
|
|
{ |
47
|
3 |
|
if (!isset(self::STORAGE_MAP[$adapterName])) |
48
|
|
|
{ |
49
|
1 |
|
throw new UnknownStorageAdapterException($adapterName, self::STORAGE_MAP); |
50
|
|
|
} |
51
|
|
|
|
52
|
2 |
|
$storageAdapterClass = self::STORAGE_MAP[$adapterName]; |
53
|
2 |
|
$this->_storage = new $storageAdapterClass; |
54
|
2 |
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param array $rules |
58
|
|
|
* @param string $storageAdapter |
59
|
|
|
* @return static |
60
|
|
|
* @throws \hamburgscleanest\GuzzleAdvancedThrottle\Exceptions\UnknownStorageAdapterException |
61
|
|
|
*/ |
62
|
3 |
|
public static function create(array $rules, string $storageAdapter = 'array') |
63
|
|
|
{ |
64
|
3 |
|
return new static($rules, $storageAdapter); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @return RequestLimitGroup |
69
|
|
|
* @throws \Exception |
70
|
|
|
*/ |
71
|
1 |
|
public function getRequestLimitGroup() : RequestLimitGroup |
72
|
|
|
{ |
73
|
1 |
|
$requestLimitGroup = new RequestLimitGroup(); |
74
|
1 |
|
foreach ($this->_rules as $rule) |
75
|
|
|
{ |
76
|
1 |
|
$requestLimitGroup->addRequestLimiter(RequestLimiter::createFromRule($rule, $this->_storage)); |
77
|
|
|
} |
78
|
|
|
|
79
|
1 |
|
return $requestLimitGroup; |
80
|
|
|
} |
81
|
|
|
} |