From 930df6cf7012ed641d28baa1615544ee84394751 Mon Sep 17 00:00:00 2001 From: MBriedis Date: Tue, 28 Apr 2015 00:32:20 +0300 Subject: [PATCH] Fix empty array validation --- src/Briedis/ApiBuilder/StructureValidator.php | 2 +- tests/SingleDepthValidatorTest.php | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/Briedis/ApiBuilder/StructureValidator.php b/src/Briedis/ApiBuilder/StructureValidator.php index f4ecb26..9b35612 100644 --- a/src/Briedis/ApiBuilder/StructureValidator.php +++ b/src/Briedis/ApiBuilder/StructureValidator.php @@ -55,7 +55,7 @@ public function validate(array $input){ // Check for missing fields foreach($this->structure->getItems() as $k => $v){ - if(!array_key_exists($k, $input)){ + if(!$v->isOptional && !array_key_exists($k, $input)){ $exception->addMissingField($k, $v); } } diff --git a/tests/SingleDepthValidatorTest.php b/tests/SingleDepthValidatorTest.php index cd732b0..7de3e17 100644 --- a/tests/SingleDepthValidatorTest.php +++ b/tests/SingleDepthValidatorTest.php @@ -100,4 +100,18 @@ public function testUnexpectedParameter(){ $this->assertTrue($caught, 'Exception is caught'); } + + public function testOptionalParameterMissing(){ + $this->s->int('missing')->optional(); + $input = []; + $this->assertTrue($this->v->validate($input), 'Optional parameter can be omitted'); + } + + public function testEmptyArrayIsValid(){ + $this->s->int('numbers')->multiple(); + $input = [ + 'numbers' => [], + ]; + $this->assertTrue($this->v->validate($input), 'Empty array is a valid type'); + } } \ No newline at end of file