ogur
ogur

Reputation: 4586

Validating files in Zend Framework 2

Examine code below, I get file from upload and I want to validate it. I check file extensiton, size and MIME. If I check them one by one results are correct, but when I use $adapter->setValidators() result is false positive.

Are ZF2 validators act in weird way or maybe I don't understand how I am supposed to use it?

CODE

<?php    
    $data = array_merge_recursive(
        $this->getRequest()->getPost()->toArray(),          
        $this->getRequest()->getFiles()->toArray()
    );

    /* set mime on server side */
    $finfo = new \finfo(FILEINFO_MIME);             
    $mimeinfo = explode(';', $finfo->file($data['upload_image']['tmp_name']));
    $data['upload_image']['type'] = $mimeinfo[0];

    $adapter = new \Zend\File\Transfer\Adapter\Http(); 

    $validatorSize = new \Zend\Validator\File\Size(10);
    $validatorExt = new \Zend\Validator\File\Extension('gif,jpg,jpeg,png');
    $validatorMime = new \Zend\Validator\File\MimeType('image/gif,image/jpg,image/jpeg,image/png');

    $results = array();
    $results['size'] = $validatorSize->isValid($data['upload_image']);
    $results['ext'] = $validatorExt->isValid($data['upload_image']);
    $results['mime'] = $validatorMime->isValid($data['upload_image']);

    $adapter->setValidators(array(
        $validatorSize,
        $validatorExt,
        $validatorMime,
    ), $data['upload_image']);

    $results['adapter'] = $adapter->isValid();

    \Zend\Debug\Debug::dump($results);
?>

RESULTS

array(4) {
  ["size"] => bool(false)
  ["ext"] => bool(true)
  ["mime"] => bool(false)
  ["adapter"] => bool(true)
}

Upvotes: 0

Views: 2720

Answers (1)

user2627106
user2627106

Reputation:

I hope I correctly understood the meaning of the question :) You can use addValidator() method, the second param is $breakChainOnFailure. Such behavior is true for the chains of validators. If you do not explicitly break, will be executed each validator.

Upvotes: 1

Related Questions