From ab8ba09b1498101cf19535c1ca55127c9c7f2087 Mon Sep 17 00:00:00 2001 From: Henrique Moody Date: Fri, 20 Feb 2015 10:26:50 -0200 Subject: [PATCH] Fix wrong behavior on AbstractRelated class The wrong behavior was that any key with `''` was considered as true even when the validator was/had NotEmpty rule. --- library/Rules/AbstractRelated.php | 7 +++- .../Respect/Validation/Rules/KeyTest.php | 39 ++++++++++++++++--- 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/library/Rules/AbstractRelated.php b/library/Rules/AbstractRelated.php index 9f9472b91..9655d2c47 100644 --- a/library/Rules/AbstractRelated.php +++ b/library/Rules/AbstractRelated.php @@ -65,12 +65,15 @@ public function check($input) public function validate($input) { - $hasReference = $this->hasReference($input); + if ($input === '') { + return true; + } + $hasReference = $this->hasReference($input); if ($this->mandatory && !$hasReference) { return false; } - return $this->decision('validate', $hasReference, $input) || $this->getReferenceValue($input) === ''; + return $this->decision('validate', $hasReference, $input); } } diff --git a/tests/library/Respect/Validation/Rules/KeyTest.php b/tests/library/Respect/Validation/Rules/KeyTest.php index 0d07b90e2..a6d292046 100644 --- a/tests/library/Respect/Validation/Rules/KeyTest.php +++ b/tests/library/Respect/Validation/Rules/KeyTest.php @@ -13,14 +13,43 @@ public function testArrayWithPresentKeyShouldReturnTrue() $this->assertTrue($validator->validate($obj)); } + public function testEmptyInputMustReturnTrue() + { + $validator = new Key('someEmptyKey'); + $input = ''; + + $this->assertTrue($validator->assert($input)); + $this->assertTrue($validator->check($input)); + $this->assertTrue($validator->validate($input)); + } + public function testArrayWithEmptyKeyShouldReturnTrue() { $validator = new Key('someEmptyKey'); - $obj = array(); - $obj['someEmptyKey'] = ''; - $this->assertTrue($validator->assert($obj)); - $this->assertTrue($validator->check($obj)); - $this->assertTrue($validator->validate($obj)); + $input = array(); + $input['someEmptyKey'] = ''; + + $this->assertTrue($validator->assert($input)); + $this->assertTrue($validator->check($input)); + $this->assertTrue($validator->validate($input)); + } + + public function testShouldHaveTheSameReturnValueForAllValidators() + { + $rule = new Key('key', new NotEmpty()); + $input = array('key' => ''); + + try { + $rule->assert($input); + $this->fail('`assert()` must throws exception'); + } catch (\Exception $e) {} + + try { + $rule->check($input); + $this->fail('`check()` must throws exception'); + } catch (\Exception $e) {} + + $this->assertFalse($rule->validate($input)); } /**