Key   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 21
c 1
b 0
f 0
dl 0
loc 51
rs 10
ccs 22
cts 22
cp 1

6 Methods

Rating   Name   Duplication   Size   Complexity  
A resource() 0 3 1
A ttl() 0 3 1
A __construct() 0 18 4
A limit() 0 3 1
A createCounter() 0 3 1
A __toString() 0 3 2
1
<?php
2
3
namespace Zenstruck\Governator;
4
5
/**
6
 * @author Kevin Bond <[email protected]>
7
 */
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
47
    {
48 21
        return $this->resource;
49
    }
50
51 113
    public function limit(): int
52
    {
53 113
        return $this->limit;
54
    }
55
56 63
    public function ttl(): int
57
    {
58 63
        return $this->ttl;
59
    }
60
}
61