Skip to content

Commit 4938c4e

Browse files
committed
Make missing files pass validation when optional flag is used.
1 parent 3de7d38 commit 4938c4e

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/Validation/Validation.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -967,6 +967,7 @@ public static function uploadError($check, $allowNoFile = false) {
967967
* - `minSize` - The minimum file size. Defaults to not checking.
968968
* - `maxSize` - The maximum file size. Defaults to not checking.
969969
* - `optional` - Whether or not this file is optional. Defaults to false.
970+
* If true a missing file will pass the validator regardless of other constraints.
970971
*
971972
* @param array $file The uploaded file data from PHP.
972973
* @param array $options An array of options for the validation.
@@ -989,6 +990,9 @@ public static function uploadedFile($file, $options = []) {
989990
if (!static::uploadError($file, $options['optional'])) {
990991
return false;
991992
}
993+
if ($options['optional'] && (int)$file['error'] === UPLOAD_ERR_NO_FILE) {
994+
return true;
995+
}
992996
if (isset($options['minSize']) && !static::fileSize($file, '>=', $options['minSize'])) {
993997
return false;
994998
}

tests/TestCase/Validation/ValidationTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2421,4 +2421,30 @@ public function testUploadedFileSize() {
24212421
$this->assertFalse(Validation::uploadedFile($file, $options), 'Too big');
24222422
}
24232423

2424+
/**
2425+
* Test uploaded file validation.
2426+
*
2427+
* @return void
2428+
*/
2429+
public function testUploadedFileNoFile() {
2430+
$file = [
2431+
'name' => '',
2432+
'tmp_name' => TEST_APP . 'webroot/img/cake.power.gif',
2433+
'error' => UPLOAD_ERR_NO_FILE,
2434+
'type' => '',
2435+
'size' => 0
2436+
];
2437+
$options = [
2438+
'optional' => true,
2439+
'minSize' => 500,
2440+
'types' => ['image/gif', 'image/png']
2441+
];
2442+
$this->assertTrue(Validation::uploadedFile($file, $options), 'No file should be ok.');
2443+
2444+
$options = [
2445+
'optional' => false
2446+
];
2447+
$this->assertFalse(Validation::uploadedFile($file, $options), 'File is required.');
2448+
}
2449+
24242450
}

0 commit comments

Comments
 (0)