Skip to content

Commit 024a3eb

Browse files
authored
Merge pull request #1 from zx5026605/feature/sms-update-allowance
新增立即提升短信报警阀接口
2 parents 756057f + c9a29bb commit 024a3eb

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

src/RateLimiter.php

+16
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,22 @@ public function getAllowance($id)
6767
return $this->maxAllowance;
6868
}
6969

70+
public function updateAllowance($id, $threshold)
71+
{
72+
$key = $this->getKey($id);
73+
$value = $this->storage->get($key);
74+
if ($value !== false) {
75+
list($allowance, $lastCheckTime) = $this->unpackValue($value);
76+
$updatedAllowance = ($allowance + $threshold) > 0 ? ($allowance + $threshold) : 0;
77+
} else {
78+
$updatedAllowance = $threshold > 0 ? $threshold : 0;
79+
}
80+
81+
$this->storage->set($this->getKey($id), $this->packValue($updatedAllowance, time()), $this->period);
82+
83+
return $updatedAllowance;
84+
}
85+
7086
public function getMaxAllowance()
7187
{
7288
return $this->maxAllowance;

tests/RateLimitTest.php

+37
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,26 @@ public function testCheckArray()
3030
$this->check($storage);
3131
}
3232

33+
public function testUpdateAllowanceRedis()
34+
{
35+
$storage = new \Codeages\RateLimiter\Storage\RedisStorage();
36+
$this->updateAllowance($storage);
37+
}
38+
39+
public function testUpdateAllowanceMySQLPDO()
40+
{
41+
$pdo = new PDO(getenv('MYSQL_DSN'), getenv('MYSQL_USER'), getenv('MYSQL_MYSQL_PASSWORD'));
42+
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
43+
$storage = new \Codeages\RateLimiter\Storage\MySQLPDOStorage($pdo);
44+
$this->updateAllowance($storage);
45+
}
46+
47+
public function testUpdateAllowanceArray()
48+
{
49+
$storage = new \Codeages\RateLimiter\Storage\ArrayStorage();
50+
$this->updateAllowance($storage);
51+
}
52+
3353
private function check($storage)
3454
{
3555
$ip = '127.0.0.1';
@@ -59,6 +79,23 @@ private function check($storage)
5979
$rateLimit->purge($ip);
6080
}
6181

82+
private function updateAllowance($storage)
83+
{
84+
$name = 'testUpdateAllowance';
85+
$rateLimit = $this->getRateLimiter($storage);
86+
87+
$this->assertEquals(self::MAX_REQUESTS, $rateLimit->updateAllowance($name, self::MAX_REQUESTS));
88+
$this->assertEquals(0, $rateLimit->updateAllowance($name, -self::MAX_REQUESTS));
89+
$this->assertEquals(0, $rateLimit->updateAllowance($name, -self::MAX_REQUESTS));
90+
91+
for ($i = 0, $j = 0; $i < self::MAX_REQUESTS; ++$i) {
92+
$j += $i;
93+
$this->assertEquals($j, $rateLimit->updateAllowance($name, $i));
94+
}
95+
96+
$rateLimit->purge($name);
97+
}
98+
6299
private function getRateLimiter(Storage $storage)
63100
{
64101
return new RateLimiter(self::NAME, self::MAX_REQUESTS, self::PERIOD, $storage);

0 commit comments

Comments
 (0)