Skip to content

Commit

Permalink
Add decrement method to the rate limiter class (#51102)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexJump24 committed Apr 17, 2024
1 parent 9b3bb15 commit d58be75
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Illuminate/Cache/RateLimiter.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,19 @@ public function increment($key, $decaySeconds = 60, $amount = 1)
return $hits;
}

/**
* Decrement the counter for a given key for a given decay time by a given amount.
*
* @param string $key
* @param int $decaySeconds
* @param int $amount
* @return int
*/
public function decrement($key, $decaySeconds = 60, $amount = 1)
{
return $this->increment($key, $decaySeconds, $amount * -1);
}

/**
* Get the number of attempts for the given key.
*
Expand Down
1 change: 1 addition & 0 deletions src/Illuminate/Support/Facades/RateLimiter.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* @method static bool tooManyAttempts(string $key, int $maxAttempts)
* @method static int hit(string $key, int $decaySeconds = 60)
* @method static int increment(string $key, int $decaySeconds = 60, int $amount = 1)
* @method static int decrement(string $key, int $decaySeconds = 60, int $amount = 1)
* @method static mixed attempts(string $key)
* @method static mixed resetAttempts(string $key)
* @method static int remaining(string $key, int $maxAttempts)
Expand Down
11 changes: 11 additions & 0 deletions tests/Cache/CacheRateLimiterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,17 @@ public function testIncrementProperlyIncrementsAttemptCount()
$rateLimiter->increment('key', 1, 5);
}

public function testDecrementProperlyDecrementsAttemptCount()
{
$cache = m::mock(Cache::class);
$cache->shouldReceive('add')->once()->with('key:timer', m::type('int'), 1)->andReturn(true);
$cache->shouldReceive('add')->once()->with('key', 0, 1)->andReturn(true);
$cache->shouldReceive('increment')->once()->with('key', -5)->andReturn(-5);
$rateLimiter = new RateLimiter($cache);

$rateLimiter->decrement('key', 1, 5);
}

public function testHitHasNoMemoryLeak()
{
$cache = m::mock(Cache::class);
Expand Down

0 comments on commit d58be75

Please sign in to comment.