Merge pull request #343 from vlucas/issue-332

detect numeric array when keys are out of order , fixes #332
This commit is contained in:
Willem Wollebrants 2021-07-06 14:22:56 +02:00 committed by GitHub
commit ba90097aa5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 59 additions and 5 deletions

View File

@ -420,9 +420,13 @@ class Validator
*/
protected function validateIn($field, $value, $params)
{
$isAssoc = array_values($params[0]) !== $params[0];
if ($isAssoc) {
$params[0] = array_keys($params[0]);
$forceAsAssociative = false;
if (isset($params[2])) {
$forceAsAssociative = (bool) $params[2];
}
if ($forceAsAssociative || $this->isAssociativeArray($params[0])) {
$params[0] = array_keys($params[0]);
}
$strict = false;
@ -443,8 +447,12 @@ class Validator
*/
protected function validateListContains($field, $value, $params)
{
$isAssoc = array_values($value) !== $value;
if ($isAssoc) {
$forceAsAssociative = false;
if (isset($params[2])) {
$forceAsAssociative = (bool) $params[2];
}
if ($forceAsAssociative || $this->isAssociativeArray($value)) {
$value = array_keys($value);
}
@ -1566,4 +1574,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;
}
}

View File

@ -4,6 +4,7 @@ use Valitron\Validator;
class ValidateTest extends BaseTestCase
{
public function testValidWithNoRules()
{
$v = new Validator(array('name' => 'Chester Tester'));
@ -2920,6 +2921,46 @@ 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' => 'c-2'));
$v->rules(array(
'in' => array(
array('color', array('c-3'=>'green', 'c-2'=>'purple'))
)
));
$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());
}
}
function sampleFunctionCallback($field, $value, array $params)