Upload and respect/validation


#1

im using respect/validation for check image in form

$validation=$this->validator->validate($request,[
‘myinputname’=>v::image(),
]);

    if($validation->failed())
    {
           //bla bla its not an image 
    }

is it an elegant way to perform this ?

knowing that

$files = $request->getUploadedFiles();
=> $files is an array and validate() refuse it


#2

well … so a temporary solution :

knowing that :

  • $request->getUploadedFiles(); is an UploadedFile object
  • UploadedFile doent have a getparam() method

to check validation you must use something like :

$validation=this->validator->validate(_FILES[‘myinput’],[
‘tmp_name’=>v::image(),
]);

My validator class :

namespace App\Validation;
use Respect\Validation\Validator as Respect;
use Respect\Validation\Exceptions\NestedValidationException;

class Validator{
protected $errors;
public function validate($request,array $rules)
{
foreach ($rules as $field => $rule) {
try{
if(is_array($request))
$rule->setName(ucfirst($field))->assert($request[$field]);
else
$rule->setName(ucfirst($field))->assert($request->getParam($field));
} catch (NestedValidationException $e){
$e->setParam(‘translator’, ‘gettext’);
$this->errors[$field] =$e->getMessages();
}
}

    $_SESSION['errors']=$this->errors;
    return $this;
}

public function failed()
{
    return !empty($this->errors);
}

}

but then you will catch errors on ‘tmp_name’ field and not in ‘myinput’ field
idem for ‘size’ and ‘type’ field

ii let this for those who are not satisfied with stackoverflow about upload/slim/validation

if you have a better solution not using $_FILES…