From 4938c4e5f66a86295ec52ec975fd95a58599a81d Mon Sep 17 00:00:00 2001 From: mark_story Date: Sat, 6 Sep 2014 22:52:17 -0400 Subject: [PATCH] Make missing files pass validation when optional flag is used. --- src/Validation/Validation.php | 4 +++ tests/TestCase/Validation/ValidationTest.php | 26 ++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/Validation/Validation.php b/src/Validation/Validation.php index 8fb55dfbaeb..660a05ed5f4 100644 --- a/src/Validation/Validation.php +++ b/src/Validation/Validation.php @@ -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. @@ -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; } diff --git a/tests/TestCase/Validation/ValidationTest.php b/tests/TestCase/Validation/ValidationTest.php index 14668194de3..28ec21e98eb 100644 --- a/tests/TestCase/Validation/ValidationTest.php +++ b/tests/TestCase/Validation/ValidationTest.php @@ -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.'); + } + }