Skip to content
Permalink
Browse files

Make uploadError() and uploadedFile() accept missing files.

This makes validating forms where there is an optional file much easier.
  • Loading branch information...
markstory committed Sep 7, 2014
1 parent 3471734 commit 3de7d38ccef3c883f18c60eb409446c5d944bd49
Showing with 19 additions and 4 deletions.
  1. +13 −4 src/Validation/Validation.php
  2. +6 −0 tests/TestCase/Validation/ValidationTest.php
@@ -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;
}
@@ -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'])) {
@@ -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));
}
/**

0 comments on commit 3de7d38

Please sign in to comment.
You can’t perform that action at this time.