diff --git a/src/Valitron/Validator.php b/src/Valitron/Validator.php index ed04d77..0c0a844 100644 --- a/src/Valitron/Validator.php +++ b/src/Valitron/Validator.php @@ -420,9 +420,8 @@ class Validator */ protected function validateIn($field, $value, $params) { - $isAssoc = array_values($params[0]) !== $params[0]; - if ($isAssoc) { - $params[0] = array_keys($params[0]); + if ($this->isAssociativeArray($params[0])) { + $params[0] = array_keys($params[0]); } $strict = false; @@ -443,8 +442,7 @@ class Validator */ protected function validateListContains($field, $value, $params) { - $isAssoc = array_values($value) !== $value; - if ($isAssoc) { + if ($this->isAssociativeArray($value)) { $value = array_keys($value); } @@ -1566,4 +1564,9 @@ class Validator $me->mapFieldRules($field, $rules[$field]); }, array_keys($rules)); } + + private function isAssociativeArray($input){ + //array contains at least one key that's not an can not be cast to an integer + return count(array_filter(array_keys($input), 'is_string')) > 0; + } } diff --git a/tests/Valitron/ValidateTest.php b/tests/Valitron/ValidateTest.php index d086ea8..58b34da 100644 --- a/tests/Valitron/ValidateTest.php +++ b/tests/Valitron/ValidateTest.php @@ -4,6 +4,7 @@ use Valitron\Validator; class ValidateTest extends BaseTestCase { + public function testValidWithNoRules() { $v = new Validator(array('name' => 'Chester Tester')); @@ -2920,6 +2921,35 @@ class ValidateTest extends BaseTestCase $v->rule('optional', 'address'); $this->assertTrue($v->validate()); } + + /** + * + * @see https://github.com/vlucas/valitron/issues/332 + */ + public function testInRuleSearchesValuesForNumericArray(){ + + $v = new Valitron\Validator(array('color' => 'purple')); + + $v->rules(array( + 'in' => array( + array('color', array(3=>'green', 2=>'purple')) + ) + )); + + $this->assertTrue($v->validate()); + } + + public function testInRuleSearchesKeysForAssociativeArray(){ + $v = new Valitron\Validator(array('color' => 'purple')); + + $v->rules(array( + 'in' => array( + array('color', array('c-3'=>'green', 'c-2'=>'purple')) + ) + )); + + $this->assertFalse($v->validate()); + } } function sampleFunctionCallback($field, $value, array $params)