Skip to content

Commit

Permalink
Add missing try/catch and refactor duplicate code.
Browse files Browse the repository at this point in the history
  • Loading branch information
markstory committed Oct 11, 2016
1 parent 30e118c commit 526e964
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 18 deletions.
46 changes: 29 additions & 17 deletions src/Validation/Validation.php
Expand Up @@ -957,17 +957,9 @@ public static function luhn($check)
*/
public static function mimeType($check, $mimeTypes = [])
{
if ($check instanceof UploadedFileInterface) {
try {
// Uploaded files throw exceptions on upload errors.
$file = $check->getStream()->getMetadata('uri');
} catch (RuntimeException $e) {
return false;
}
} elseif (is_array($check) && isset($check['tmp_name'])) {
$file = $check['tmp_name'];
} else {
$file = $check;
$file = static::getFilename($check);
if ($file === false) {
return false;
}

if (!function_exists('finfo_open')) {
Expand Down Expand Up @@ -998,6 +990,29 @@ public static function mimeType($check, $mimeTypes = [])
return in_array($mime, $mimeTypes);
}

/**
* Helper for reading the file out of the various file implementations
* we accept.
*
* @param string|array|\Psr\Http\Message\UploadedFileInterface $check The data to read a filename out of.
* @return string|bool Either the filename or false on failure.
*/
protected static function getFilename($check)
{
if ($check instanceof UploadedFileInterface) {
try {
// Uploaded files throw exceptions on upload errors.
return $check->getStream()->getMetadata('uri');
} catch (RuntimeException $e) {
return false;
}
}
if (is_array($check) && isset($check['tmp_name'])) {
return $check['tmp_name'];
}
return $check;
}

/**
* Checks the filesize
*
Expand All @@ -1012,12 +1027,9 @@ public static function mimeType($check, $mimeTypes = [])
*/
public static function fileSize($check, $operator = null, $size = null)
{
if ($check instanceof UploadedFileInterface) {
$file = $check->getStream()->getMetadata('uri');
} elseif (is_array($check) && isset($check['tmp_name'])) {
$file = $check['tmp_name'];
} else {
$file = $check;
$file = static::getFilename($check);
if ($file === false) {
return false;
}

if (is_string($size)) {
Expand Down
2 changes: 1 addition & 1 deletion tests/TestCase/Validation/ValidationTest.php
Expand Up @@ -21,8 +21,8 @@
use Cake\TestSuite\TestCase;
use Cake\Validation\Validation;
use Cake\Validation\Validator;
use Zend\Diactoros\UploadedFile;
use Locale;
use Zend\Diactoros\UploadedFile;

require_once __DIR__ . '/stubs.php';

Expand Down

0 comments on commit 526e964

Please sign in to comment.