Total Complexity | 10 |
Total Lines | 51 |
Duplicated Lines | 0 % |
Coverage | 100% |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
1 | <?php |
||
8 | final class Key |
||
9 | { |
||
10 | private string $resource; |
||
11 | private int $limit; |
||
12 | private int $ttl; |
||
13 | private string $prefix; |
||
14 | private ?string $string = null; |
||
15 | |||
16 | 122 | public function __construct(string $resource, int $limit, int $ttl, string $prefix = '') |
|
17 | { |
||
18 | 122 | if (empty($resource)) { |
|
19 | 1 | throw new \InvalidArgumentException('A non-empty string is required for a throttle\'s "resource".'); |
|
20 | } |
||
21 | |||
22 | 121 | if ($limit < 1) { |
|
23 | 2 | throw new \InvalidArgumentException('A positive integer is required for a throttle\'s "limit".'); |
|
24 | } |
||
25 | |||
26 | 119 | if ($ttl < 1) { |
|
27 | 2 | throw new \InvalidArgumentException('A positive number is required for a throttle\'s "time to live".'); |
|
28 | } |
||
29 | |||
30 | 117 | $this->resource = $resource; |
|
31 | 117 | $this->limit = $limit; |
|
32 | 117 | $this->ttl = $ttl; |
|
33 | 117 | $this->prefix = $prefix; |
|
34 | 117 | } |
|
35 | |||
36 | 111 | public function __toString(): string |
|
37 | { |
||
38 | 111 | return $this->string ?: $this->string = $this->prefix.\rtrim(\strtr(\base64_encode($this->resource), '+/', '-_'), '=').$this->limit.$this->ttl; |
|
39 | } |
||
40 | |||
41 | 62 | public function createCounter(): Counter |
|
42 | { |
||
43 | 62 | return new Counter(0, time() + $this->ttl); |
|
44 | } |
||
45 | |||
46 | 21 | public function resource(): string |
|
49 | } |
||
50 | |||
51 | 113 | public function limit(): int |
|
52 | { |
||
53 | 113 | return $this->limit; |
|
54 | } |
||
55 | |||
56 | 63 | public function ttl(): int |
|
59 | } |
||
60 | } |
||
61 |