From d58be75cb219f1288683cfb6583c65a222febf80 Mon Sep 17 00:00:00 2001 From: Alex Williams Date: Wed, 17 Apr 2024 20:43:36 +0100 Subject: [PATCH] Add decrement method to the rate limiter class (#51102) --- src/Illuminate/Cache/RateLimiter.php | 13 +++++++++++++ src/Illuminate/Support/Facades/RateLimiter.php | 1 + tests/Cache/CacheRateLimiterTest.php | 11 +++++++++++ 3 files changed, 25 insertions(+) diff --git a/src/Illuminate/Cache/RateLimiter.php b/src/Illuminate/Cache/RateLimiter.php index afdb9b25a208..f6116df4f92a 100644 --- a/src/Illuminate/Cache/RateLimiter.php +++ b/src/Illuminate/Cache/RateLimiter.php @@ -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. * diff --git a/src/Illuminate/Support/Facades/RateLimiter.php b/src/Illuminate/Support/Facades/RateLimiter.php index e8b3ab3fe4f5..cab2d444e26e 100644 --- a/src/Illuminate/Support/Facades/RateLimiter.php +++ b/src/Illuminate/Support/Facades/RateLimiter.php @@ -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) diff --git a/tests/Cache/CacheRateLimiterTest.php b/tests/Cache/CacheRateLimiterTest.php index 0805f92af092..b1cbec87598a 100644 --- a/tests/Cache/CacheRateLimiterTest.php +++ b/tests/Cache/CacheRateLimiterTest.php @@ -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);