Skip to content

Commit

Permalink
Make missing files pass validation when optional flag is used.
Browse files Browse the repository at this point in the history
  • Loading branch information
markstory committed Sep 7, 2014
1 parent 3de7d38 commit 4938c4e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Validation/Validation.php
Expand Up @@ -967,6 +967,7 @@ public static function uploadError($check, $allowNoFile = false) {
* - `minSize` - The minimum file size. Defaults to not checking.
* - `maxSize` - The maximum file size. Defaults to not checking.
* - `optional` - Whether or not this file is optional. Defaults to false.
* If true a missing file will pass the validator regardless of other constraints.
*
* @param array $file The uploaded file data from PHP.
* @param array $options An array of options for the validation.
Expand All @@ -989,6 +990,9 @@ public static function uploadedFile($file, $options = []) {
if (!static::uploadError($file, $options['optional'])) {
return false;
}
if ($options['optional'] && (int)$file['error'] === UPLOAD_ERR_NO_FILE) {
return true;
}
if (isset($options['minSize']) && !static::fileSize($file, '>=', $options['minSize'])) {
return false;
}
Expand Down
26 changes: 26 additions & 0 deletions tests/TestCase/Validation/ValidationTest.php
Expand Up @@ -2421,4 +2421,30 @@ public function testUploadedFileSize() {
$this->assertFalse(Validation::uploadedFile($file, $options), 'Too big');
}

/**
* Test uploaded file validation.
*
* @return void
*/
public function testUploadedFileNoFile() {
$file = [
'name' => '',
'tmp_name' => TEST_APP . 'webroot/img/cake.power.gif',
'error' => UPLOAD_ERR_NO_FILE,
'type' => '',
'size' => 0
];
$options = [
'optional' => true,
'minSize' => 500,
'types' => ['image/gif', 'image/png']
];
$this->assertTrue(Validation::uploadedFile($file, $options), 'No file should be ok.');

$options = [
'optional' => false
];
$this->assertFalse(Validation::uploadedFile($file, $options), 'File is required.');
}

}

0 comments on commit 4938c4e

Please sign in to comment.