Skip to content

Commit

Permalink
Make uploadError() and uploadedFile() accept missing files.
Browse files Browse the repository at this point in the history
This makes validating forms where there is an optional file much easier.
  • Loading branch information
markstory committed Sep 7, 2014
1 parent 3471734 commit 3de7d38
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/Validation/Validation.php
Expand Up @@ -939,14 +939,17 @@ public static function fileSize($check, $operator = null, $size = null) {
* Checking for upload errors
*
* @param string|array $check Value to check.
* @param bool $allowNoFile Set to true to allow UPLOAD_ERR_NO_FILE as a pass.
* @return bool
* @see http://www.php.net/manual/en/features.file-upload.errors.php
*/
public static function uploadError($check) {
public static function uploadError($check, $allowNoFile = false) {
if (is_array($check) && isset($check['error'])) {
$check = $check['error'];
}

if ($allowNoFile) {
return in_array((int)$check, [UPLOAD_ERR_OK, UPLOAD_ERR_NO_FILE], true);
}
return (int)$check === UPLOAD_ERR_OK;
}

Expand All @@ -963,21 +966,27 @@ public static function uploadError($check) {
* the file type will be checked with ext/finfo.
* - `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.
*
* @param array $file The uploaded file data from PHP.
* @param array $options An array of options for the validation.
* @return bool
*/
public static function uploadedFile($file, $options = []) {
$options += ['minSize' => null, 'maxSize' => null, 'types' => null];
$options += [
'minSize' => null,
'maxSize' => null,
'types' => null,
'optional' => false,
];
if (!is_array($file)) {
return false;
}
$keys = ['name', 'tmp_name', 'error', 'type', 'size'];
if (array_keys($file) != $keys) {
return false;
}
if (!static::uploadError($file)) {
if (!static::uploadError($file, $options['optional'])) {
return false;
}
if (isset($options['minSize']) && !static::fileSize($file, '>=', $options['minSize'])) {
Expand Down
6 changes: 6 additions & 0 deletions tests/TestCase/Validation/ValidationTest.php
Expand Up @@ -2322,6 +2322,12 @@ public function testUploadError() {
$this->assertFalse(Validation::uploadError(2));
$this->assertFalse(Validation::uploadError(array('error' => 2)));
$this->assertFalse(Validation::uploadError(array('error' => '2')));

$this->assertFalse(Validation::uploadError(UPLOAD_ERR_NO_FILE));
$this->assertFalse(Validation::uploadError(UPLOAD_ERR_FORM_SIZE, true));
$this->assertFalse(Validation::uploadError(UPLOAD_ERR_INI_SIZE, true));
$this->assertFalse(Validation::uploadError(UPLOAD_ERR_NO_TMP_DIR, true));
$this->assertTrue(Validation::uploadError(UPLOAD_ERR_NO_FILE, true));
}

/**
Expand Down

0 comments on commit 3de7d38

Please sign in to comment.