gothinkster / slim-php-realworld-example-app

Exemplary real world application built with Slim
https://realworld.io
427 stars 96 forks source link

Problems whit validateArray #10

Closed GoldraK closed 6 years ago

GoldraK commented 6 years ago

I am using your development to make a new API.

But I have encountered a problem with validateArray and can not use the when option

I have the following data array:

$ values ​​["name"] = "second order";
$ values ​​["use_building"] = 8;
$ values ​​["other_use_building"] = "cave";

The validation has to check that when use_building is 8 the other_use_building is not empty.

If I perform the validation in a file for tests, the following validation works correctly:

$buildingValidator = v::key('use_building', v::optional(v::intVal()))
    ->when(v::key('use_building', v::equals(8)),
        v::key('other_use_building', v::notEmpty()),
        v::key('use_building', v::optional(v::intVal()))
    );

var_dump($buildingValidator->validate($values));

But when I enter it in the validateArray system

return $this->validator->validateArray($values,
            [
                'name' => v::notOptional()
                    ->notEmpty(),
                'use_building' => v::optional(
                    v::intVal()
                ),
                'other_use_building' =>
                    v::key('use_building', v::optional(v::intVal()))
                        ->when(v::key('use_building', v::equals(8)),
                            v::key('other_use_building', v::notEmpty()),
                            v::key('use_building', v::optional(v::intVal()))
                        )
            ]);

tells me what error when he had to see given true


  ["errors":protected]=>
  array(1) {
    ["other_use_building"]=>
    array(2) {
      [0]=>
      string(32) "Key use_building must be present"
      [1]=>
      string(32) "Key use_building must be present"
    }
  }
}```

Thanks for the help
alhoqbani commented 6 years ago

I'm not an expert in the Respect\Validation library, but I think to have conditional rules based on another field's, we must pass the complete data to validate.

The validateArray method passes a single value for each rule, unlike your example where you pass the whole $values array. So, when we validate the field other_use_building we pass only the value for this field. Hence, the error Key use_building must be present.

Try replacing this line

$rule->setName($field)->assert($this->getValue($values, $field));

with

$rule->setName($field)->assert($values);

I haven't tested this change, it might work or you may need to define your logic for you specific use case.

GoldraK commented 6 years ago

Thanks, go to see