Skip to content

Commit

Permalink
[11.x] Pass decay seconds or minutes like hour and day (#51054)
Browse files Browse the repository at this point in the history
* Allow overwriting the default decay time

* Verify that default decay times are able to be chagned
  • Loading branch information
jimmypuckett authored Apr 15, 2024
1 parent ad00a85 commit 645f57a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/Illuminate/Cache/RateLimiting/Limit.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,22 +51,24 @@ public function __construct($key = '', int $maxAttempts = 60, int $decaySeconds
* Create a new rate limit.
*
* @param int $maxAttempts
* @param int $decaySeconds
* @return static
*/
public static function perSecond($maxAttempts)
public static function perSecond($maxAttempts, $decaySeconds = 1)
{
return new static('', $maxAttempts, 1);
return new static('', $maxAttempts, $decaySeconds);
}

/**
* Create a new rate limit.
*
* @param int $maxAttempts
* @param int $decayMinutes
* @return static
*/
public static function perMinute($maxAttempts)
public static function perMinute($maxAttempts, $decayMinutes = 1)
{
return new static('', $maxAttempts, 60);
return new static('', $maxAttempts, 60 * $decayMinutes);
}

/**
Expand Down
16 changes: 16 additions & 0 deletions tests/Cache/LimitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,18 @@ public function testConstructors()
$this->assertSame(1, $limit->decaySeconds);
$this->assertSame(3, $limit->maxAttempts);

$limit = Limit::perSecond(3, 5);
$this->assertSame(5, $limit->decaySeconds);
$this->assertSame(3, $limit->maxAttempts);

$limit = Limit::perMinute(3);
$this->assertSame(60, $limit->decaySeconds);
$this->assertSame(3, $limit->maxAttempts);

$limit = Limit::perMinute(3, 4);
$this->assertSame(240, $limit->decaySeconds);
$this->assertSame(3, $limit->maxAttempts);

$limit = Limit::perMinutes(2, 3);
$this->assertSame(120, $limit->decaySeconds);
$this->assertSame(3, $limit->maxAttempts);
Expand All @@ -30,10 +38,18 @@ public function testConstructors()
$this->assertSame(3600, $limit->decaySeconds);
$this->assertSame(3, $limit->maxAttempts);

$limit = Limit::perHour(3, 2);
$this->assertSame(7200, $limit->decaySeconds);
$this->assertSame(3, $limit->maxAttempts);

$limit = Limit::perDay(3);
$this->assertSame(86400, $limit->decaySeconds);
$this->assertSame(3, $limit->maxAttempts);

$limit = Limit::perDay(3, 5);
$this->assertSame(432000, $limit->decaySeconds);
$this->assertSame(3, $limit->maxAttempts);

$limit = new GlobalLimit(3);
$this->assertSame(60, $limit->decaySeconds);
$this->assertSame(3, $limit->maxAttempts);
Expand Down

0 comments on commit 645f57a

Please sign in to comment.