Key::__toString()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
ccs 2
cts 2
cp 1
cc 2
nc 1
nop 0
crap 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