refactored file validator.

This commit is contained in:
Qiang Xue
2014-06-14 16:21:59 -04:00
parent c42942a0b8
commit 084819b84c
4 changed files with 50 additions and 39 deletions

View File

@ -139,22 +139,17 @@ class BaseFileHelper
* This method will use a local map between extension names and MIME types.
* @param string $file the file name.
* @param string $magicFile the path of the file that contains all available MIME type information.
* If this is not set, the default file aliased by `@yii/util/mimeTypes.php` will be used.
* If this is not set, the default file aliased by `@yii/helpers/mimeTypes.php` will be used.
* @return string the MIME type. Null is returned if the MIME type cannot be determined.
*/
public static function getMimeTypeByExtension($file, $magicFile = null)
{
static $mimeTypes = [];
if ($magicFile === null) {
$magicFile = __DIR__ . '/mimeTypes.php';
}
if (!isset($mimeTypes[$magicFile])) {
$mimeTypes[$magicFile] = require($magicFile);
}
$mimeTypes = static::loadMimeTypes($magicFile);
if (($ext = pathinfo($file, PATHINFO_EXTENSION)) !== '') {
$ext = strtolower($ext);
if (isset($mimeTypes[$magicFile][$ext])) {
return $mimeTypes[$magicFile][$ext];
if (isset($mimeTypes[$ext])) {
return $mimeTypes[$ext];
}
}
@ -162,23 +157,36 @@ class BaseFileHelper
}
/**
* Determines the extensions by given mime-type.
* Determines the extensions by given MIME type.
* This method will use a local map between extension names and MIME types.
* @param string $mimeType file mime-type.
* @param string $mimeType file MIME type.
* @param string $magicFile the path of the file that contains all available MIME type information.
* If this is not set, the default file aliased by `@yii/util/mimeTypes.php` will be used.
* @return array.
* If this is not set, the default file aliased by `@yii/helpers/mimeTypes.php` will be used.
* @return array the extensions corresponding to the specified MIME type
*/
public static function getExtensionsByMimeType($mimeType, $magicFile = null)
{
static $mimeTypes = [];
$mimeTypes = static::loadMimeTypes($magicFile);
return array_keys($mimeTypes, mb_strtolower($mimeType, 'utf-8'), true);
}
if (!count($mimeTypes)) {
private static $_mimeTypes = [];
/**
* Loads MIME types from the specified file.
* @param string $magicFile the file that contains MIME type information.
* If null, the file `@yii/helpers/mimeTypes.php` will be used.
* @return array the mapping from file extensions to MIME types
*/
protected static function loadMimeTypes($magicFile)
{
if ($magicFile === null) {
$magicFile = __DIR__ . '/mimeTypes.php';
$mimeTypes = require($magicFile);
}
return array_keys($mimeTypes, mb_strtolower($mimeType, 'utf-8'));
if (!isset(self::$_mimeTypes[$magicFile])) {
self::$_mimeTypes[$magicFile] = require($magicFile);
}
return self::$_mimeTypes[$magicFile];
}
/**