0

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)
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm that was helpful, I changed my code a bit and now it's working correctly (for me). Thx, enjoy your first reputation points :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.