Browse Source

Make missing files pass validation when optional flag is used.

mark_story 11 years ago
parent
commit
4938c4e5f6
2 changed files with 30 additions and 0 deletions
  1. 4 0
      src/Validation/Validation.php
  2. 26 0
      tests/TestCase/Validation/ValidationTest.php

+ 4 - 0
src/Validation/Validation.php

@@ -967,6 +967,7 @@ class Validation {
  * - `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.
@@ -989,6 +990,9 @@ class Validation {
 		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;
 		}

+ 26 - 0
tests/TestCase/Validation/ValidationTest.php

@@ -2421,4 +2421,30 @@ class ValidationTest extends TestCase {
 		$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.');
+	}
+
 }