Skip to content

Commit 47c4c9c

Browse files
committed
fix: tokenTime calcuration
When check() returns false, tokenTime is 0.
1 parent 10f772a commit 47c4c9c

2 files changed

Lines changed: 6 additions & 6 deletions

File tree

system/Throttle/Throttler.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ public function check(string $key, int $capacity, int $seconds, int $cost = 1):
107107
$this->cache->save($tokenName, $tokens, $seconds);
108108
$this->cache->save($tokenName . 'Time', $this->time(), $seconds);
109109

110-
$this->tokenTime = max(1, (int) $refresh);
110+
$this->tokenTime = 0;
111111

112112
return true;
113113
}
@@ -130,7 +130,7 @@ public function check(string $key, int $capacity, int $seconds, int $cost = 1):
130130
$this->cache->save($tokenName, $tokens, $seconds);
131131
$this->cache->save($tokenName . 'Time', $this->time(), $seconds);
132132

133-
$this->tokenTime = max(1, (int) ($refresh - $elapsed));
133+
$this->tokenTime = 0;
134134

135135
return true;
136136
}

tests/system/Throttle/ThrottleTest.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,11 +36,11 @@ public function testTokenTime()
3636
// set $rate
3737
$rate = 1; // allow 1 request per minute
3838

39-
// first check just creates a bucket, so tokenTime should be 0
39+
// When the first check you have a token, so tokenTime should be 0
4040
$throttler->check('127.0.0.1', $rate, MINUTE);
4141
$this->assertSame(0, $throttler->getTokenTime());
4242

43-
// additional check affects tokenTime, so tokenTime should be 1 or greater
43+
// When additional check you don't have one token, so tokenTime should be 1 or greater
4444
$throttler->check('127.0.0.1', $rate, MINUTE);
4545
$this->assertGreaterThanOrEqual(1, $throttler->getTokenTime());
4646
}
@@ -64,15 +64,15 @@ public function testTokenTimeCalculation()
6464
// token should be 2
6565
$this->assertTrue($throttler->check('test', $capacity, $seconds));
6666
// token should be 2 - 1 = 1
67-
$this->assertSame(100, $throttler->getTokenTime(), 'Wrong token time');
67+
$this->assertSame(0, $throttler->getTokenTime(), 'Wrong token time');
6868

6969
// do nothing for 3 seconds
7070
$throttler = $throttler->setTestTime($time + 3);
7171

7272
// token should be 1 + 3 * 0.01 = 1.03
7373
$this->assertTrue($throttler->check('test', $capacity, $seconds));
7474
// token should be 1.03 - 1 = 0.03
75-
$this->assertSame(97, $throttler->getTokenTime(), 'Wrong token time');
75+
$this->assertSame(0, $throttler->getTokenTime(), 'Wrong token time');
7676

7777
$this->assertFalse($throttler->check('test', $capacity, $seconds));
7878
// token should still be 0.03 because check failed

0 commit comments

Comments
 (0)