From 2d54a4cdff4e619bdeaaccca9ad884e5e7da838b Mon Sep 17 00:00:00 2001 From: Tom Date: Thu, 16 Apr 2015 15:43:48 +0100 Subject: [PATCH] Adding the "isBetween" function to the validator. isBetween can be used to check whether a parameter be between two specified boundary values. --- README.md | 1 + src/Klein/Validator.php | 3 ++ tests/Klein/Tests/ValidationsTest.php | 58 +++++++++++++++++++++++++++ 3 files changed, 62 insertions(+) diff --git a/README.md b/README.md index 6fafb862..001d49c5 100644 --- a/README.md +++ b/README.md @@ -383,6 +383,7 @@ $validator-> isLen($length) // The string must be the exact length isLen($min, $max) // The string must be between $min and $max length (inclusive) isInt() // Check for a valid integer + isBetween($min, $max) // The number must be between $min and $max (inclusive) isFloat() // Check for a valid float/decimal isEmail() // Check for a valid email isUrl() // Check for a valid URL diff --git a/src/Klein/Validator.php b/src/Klein/Validator.php index 6efaf761..aa027833 100644 --- a/src/Klein/Validator.php +++ b/src/Klein/Validator.php @@ -90,6 +90,9 @@ public static function addDefault() static::$methods['int'] = function ($str) { return (string)$str === ((string)(int)$str); }; + static::$methods['between'] = function ($str, $min, $max) { + return (real)$str >= $min && (real)$str <= $max; + }; static::$methods['float'] = function ($str) { return (string)$str === ((string)(float)$str); }; diff --git a/tests/Klein/Tests/ValidationsTest.php b/tests/Klein/Tests/ValidationsTest.php index 30ce6828..15e10048 100644 --- a/tests/Klein/Tests/ValidationsTest.php +++ b/tests/Klein/Tests/ValidationsTest.php @@ -217,6 +217,64 @@ function ($request, $response, $service) { ); } + public function testBetween() + { + $this->klein_app->respond( + '/[:test_param]', + function ($request, $response, $service) { + $service->validateParam('test_param') + ->notNull() + ->isBetween(0, 5); + + // We should only get here if we passed our validations + echo 'yup!'; + } + ); + + $this->assertSame( + 'fail', + $this->dispatchAndReturnOutput( + MockRequestFactory::create('/-1') + ) + ); + $this->assertSame( + 'yup!', + $this->dispatchAndReturnOutput( + MockRequestFactory::create('/0') + ) + ); + $this->assertSame( + 'yup!', + $this->dispatchAndReturnOutput( + MockRequestFactory::create('/3') + ) + ); + $this->assertSame( + 'yup!', + $this->dispatchAndReturnOutput( + MockRequestFactory::create('/5') + ) + ); + $this->assertSame( + 'yup!', + $this->dispatchAndReturnOutput( + MockRequestFactory::create('/3.0') + ) + ); + $this->assertSame( + 'yup!', + $this->dispatchAndReturnOutput( + MockRequestFactory::create('/2e0') + ) + ); + $this->assertSame( + 'fail', + $this->dispatchAndReturnOutput( + MockRequestFactory::create('/10,000') + ) + ); + } + public function testFloat() { $this->klein_app->respond(