-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRestEndpointTimedRateLimit.php
More file actions
55 lines (46 loc) · 1.65 KB
/
RestEndpointTimedRateLimit.php
File metadata and controls
55 lines (46 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
namespace lewiscowles\HTTP\REST;
use lewiscowles\CreditHandlerInterface;
use lewiscowles\CreditDataInterface;
use lewiscowles\storage\TTLStorageInterface;
use lewiscowles\HTTP\REST\RestEndpointCreditData;
class RestEndpointTimedRateLimit implements CreditHandlerInterface {
protected $HashId;
protected $Time;
protected $Credits;
protected $Storage;
protected $Ttl;
public function __construct(string $hash_id, int $time, int $credits,
TTLStorageInterface $ttsi, int $ttl) {
$this->HashId = $hash_id;
$this->Time = $time;
$this->Credits = $credits;
$this->Storage = $ttsi;
$this->Ttl = $ttl;
}
public function getCreditData() : CreditDataInterface {
return $this->Storage->get($this->HashId, new RestEndpointCreditData(
$this->Time, $this->Credits
));
}
public function checkCreditData(CreditDataInterface $data) : bool {
return ($data->getBalance() > 0);
}
public function setCreditData(CreditDataInterface $data) {
$this->Storage->set($this->HashId, $data, $this->getRefreshTtl($data));
}
public function formatCreditReload(CreditDataInterface $data) : string {
$refresh = $this->getRefreshTtl($data);
$out = date('s', $refresh).' seconds';
if($refresh > 60) {
$out = date('i', $refresh).' minutes, ' . $out;
}
if($refresh > 3600) {
$out = intval($refresh / 3600).' hours, '.$out;
}
return $out;
}
protected function getRefreshTtl(CreditDataInterface $data) {
return ($this->Ttl - ($this->Time - $data->getCreated()));
}
}