From be8cb9e074ce2dbf1a47d8a61a450f8fb2712420 Mon Sep 17 00:00:00 2001 From: Willem Wollebrants Date: Tue, 6 Jul 2021 10:58:22 +0200 Subject: [PATCH] add parameter to force in and listContains to look at array keys --- src/Valitron/Validator.php | 13 +++++++++++-- tests/Valitron/ValidateTest.php | 15 +++++++++++++-- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/Valitron/Validator.php b/src/Valitron/Validator.php index 0c0a844..6555384 100644 --- a/src/Valitron/Validator.php +++ b/src/Valitron/Validator.php @@ -420,7 +420,11 @@ class Validator */ protected function validateIn($field, $value, $params) { - if ($this->isAssociativeArray($params[0])) { + $forceAsAssociative = false; + if (isset($params[2])) { + $forceAsAssociative = (bool) $params[2]; + } + if ($this->isAssociativeArray($params[0]) || $forceAsAssociative) { $params[0] = array_keys($params[0]); } @@ -442,7 +446,12 @@ class Validator */ protected function validateListContains($field, $value, $params) { - if ($this->isAssociativeArray($value)) { + $forceAsAssociative = false; + if (isset($params[2])) { + $forceAsAssociative = (bool) $params[2]; + } + + if ($this->isAssociativeArray($value) || $forceAsAssociative) { $value = array_keys($value); } diff --git a/tests/Valitron/ValidateTest.php b/tests/Valitron/ValidateTest.php index 58b34da..de06b61 100644 --- a/tests/Valitron/ValidateTest.php +++ b/tests/Valitron/ValidateTest.php @@ -2940,7 +2940,7 @@ class ValidateTest extends BaseTestCase } public function testInRuleSearchesKeysForAssociativeArray(){ - $v = new Valitron\Validator(array('color' => 'purple')); + $v = new Valitron\Validator(array('color' => 'c-2')); $v->rules(array( 'in' => array( @@ -2948,7 +2948,18 @@ class ValidateTest extends BaseTestCase ) )); - $this->assertFalse($v->validate()); + $this->assertTrue($v->validate()); + } + + public function testInRuleSearchesKeysWhenForcedTo(){ + $v = new Valitron\Validator(array('color' => 2)); + + $v->rules(array( + 'in' => array( + array('color', array('3'=>'green', '2'=>'purple'), null, true) + ) + )); + $this->assertTrue($v->validate()); } }