From 8004499edce52e5c4041b14f2bddf4c36156b524 Mon Sep 17 00:00:00 2001 From: Baudev Date: Tue, 9 Jul 2019 22:12:28 +0200 Subject: [PATCH 1/2] Fix bug concerning null ApiRateLimit instance in RateLimitHandler --- Service/RateLimitHandler.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Service/RateLimitHandler.php b/Service/RateLimitHandler.php index 9fc93d3..8d6b3ea 100644 --- a/Service/RateLimitHandler.php +++ b/Service/RateLimitHandler.php @@ -151,7 +151,9 @@ public function handle(Request $request) if (null !== $annotation) { $this->enabled = $annotation->enabled; - } + } else { + $annotation = new ApiRateLimit(); + } list($key, $limit, $period) = $this->getThrottle($request, $annotation); From 1f9a119e6ad2c7e2c10c1b385ea4a1ee39f91824 Mon Sep 17 00:00:00 2001 From: Baudev Date: Tue, 9 Jul 2019 22:27:36 +0200 Subject: [PATCH 2/2] Support request methods selection --- Annotation/ApiRateLimit.php | 6 ++++++ Resources/doc/usage.md | 4 +++- Service/RateLimitHandler.php | 4 ++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Annotation/ApiRateLimit.php b/Annotation/ApiRateLimit.php index 524972c..91578fd 100644 --- a/Annotation/ApiRateLimit.php +++ b/Annotation/ApiRateLimit.php @@ -28,4 +28,10 @@ final class ApiRateLimit * @var array */ public $throttle = []; + + /** + * @var array + * @example ["GET", "POST"] + */ + public $methods = []; } diff --git a/Resources/doc/usage.md b/Resources/doc/usage.md index a77299e..ae54dde 100644 --- a/Resources/doc/usage.md +++ b/Resources/doc/usage.md @@ -101,6 +101,7 @@ Configuration per resource ------------------------------- If you wish to configure the rate limits differently on some resources, you can use the `ApiRateLimit` annotation and set the `throttle` property in the same way you do in your main configuration. +You can define a rate limits only for some specific methods using `methods` property (by default `null` to cover all the different methods). You can also choose to enable or disable rate limiting by using the `enabled` property. ```php @@ -128,7 +129,8 @@ use Indragunawan\ApiRateLimitBundle\Annotation\ApiRateLimit; * "period"=10 * } * } - * } + * }, + * methods={"GET", "DELETE"} * ) */ class Foo diff --git a/Service/RateLimitHandler.php b/Service/RateLimitHandler.php index 8d6b3ea..b0f86af 100644 --- a/Service/RateLimitHandler.php +++ b/Service/RateLimitHandler.php @@ -151,6 +151,10 @@ public function handle(Request $request) if (null !== $annotation) { $this->enabled = $annotation->enabled; + if(!in_array($request->getMethod(), array_map('strtoupper', $annotation->methods)) && !empty($annotation->methods)) { + // The annotation is ignored as the method is not corresponding + $annotation = new ApiRateLimit(); + } } else { $annotation = new ApiRateLimit(); }