From 84bc08ad245aeb69ec4b2e974136caffd524cdf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Po=C5=A1a?= Date: Fri, 17 May 2024 16:37:45 +0200 Subject: [PATCH] Add RuntimeConfigurableRateLimiter (#57) --- src/RuntimeConfigurableRateLimiter.php | 41 ++++++++++++++++++++ tests/RuntimeConfigurableRateLimiterTest.php | 35 +++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 src/RuntimeConfigurableRateLimiter.php create mode 100644 tests/RuntimeConfigurableRateLimiterTest.php diff --git a/src/RuntimeConfigurableRateLimiter.php b/src/RuntimeConfigurableRateLimiter.php new file mode 100644 index 0000000..e023bbe --- /dev/null +++ b/src/RuntimeConfigurableRateLimiter.php @@ -0,0 +1,41 @@ +rateLimiter instanceof RateLimiter) { + throw new LogicException('Decorated Rate Limiter must implement RateLimiter interface'); + } + + if ($this->rateLimiter instanceof ConfigurableRateLimiter) { + $this->rateLimiter->rate = $rate; + } + + $this->rateLimiter->limit($identifier); + } + + public function limitSilently(string $identifier, Rate $rate = null): Status + { + if (!$this->rateLimiter instanceof SilentRateLimiter) { + throw new LogicException('Decorated Rate Limiter must implement SilentRateLimiter interface'); + } + + if ($this->rateLimiter instanceof ConfigurableRateLimiter) { + $this->rateLimiter->rate = $rate; + } + + return $this->rateLimiter->limitSilently($identifier); + } +} diff --git a/tests/RuntimeConfigurableRateLimiterTest.php b/tests/RuntimeConfigurableRateLimiterTest.php new file mode 100644 index 0000000..eaafc6f --- /dev/null +++ b/tests/RuntimeConfigurableRateLimiterTest.php @@ -0,0 +1,35 @@ +limitSilently($identifier, $rate); + + try { + $rateLimiter->limit($identifier, $rate); + + $this->fail('Limit should have been reached'); + } catch (LimitExceeded $exception) { + $this->assertSame($identifier, $exception->getIdentifier()); + $this->assertSame($rate, $exception->getRate()); + } + } +}