Class yii\helpers\BaseFileHelper
Inheritance | yii\helpers\BaseFileHelper |
---|---|
Subclasses | luya\helpers\FileHelper, luya\yii\helpers\FileHelper, yii\helpers\FileHelper |
Available since version | 2.0 |
Source Code | https://github.com/yiisoft/yii2/blob/master/framework/helpers/BaseFileHelper.php |
BaseFileHelper provides concrete implementation for yii\helpers\FileHelper.
Do not use BaseFileHelper. Use yii\helpers\FileHelper instead.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$mimeAliasesFile | string | The path (or alias) of a PHP file containing MIME aliases. | yii\helpers\BaseFileHelper |
$mimeMagicFile | string | The path (or alias) of a PHP file containing MIME type information. | yii\helpers\BaseFileHelper |
Public Methods
Method | Description | Defined By |
---|---|---|
changeOwnership() | Changes the Unix user and/or group ownership of a file or directory, and optionally the mode. | yii\helpers\BaseFileHelper |
copyDirectory() | Copies a whole directory as another one. | yii\helpers\BaseFileHelper |
createDirectory() | Creates a new directory. | yii\helpers\BaseFileHelper |
filterPath() | Checks if the given file path satisfies the filtering options. | yii\helpers\BaseFileHelper |
findDirectories() | Returns the directories found under the specified directory and subdirectories. | yii\helpers\BaseFileHelper |
findFiles() | Returns the files found under the specified directory and subdirectories. | yii\helpers\BaseFileHelper |
getExtensionsByMimeType() | Determines the extensions by given MIME type. | yii\helpers\BaseFileHelper |
getMimeType() | Determines the MIME type of the specified file. | yii\helpers\BaseFileHelper |
getMimeTypeByExtension() | Determines the MIME type based on the extension name of the specified file. | yii\helpers\BaseFileHelper |
localize() | Returns the localized version of a specified file. | yii\helpers\BaseFileHelper |
normalizePath() | Normalizes a file/directory path. | yii\helpers\BaseFileHelper |
removeDirectory() | Removes a directory (and all its content) recursively. | yii\helpers\BaseFileHelper |
unlink() | Removes a file or symlink in a cross-platform way | yii\helpers\BaseFileHelper |
Protected Methods
Method | Description | Defined By |
---|---|---|
loadMimeAliases() | Loads MIME aliases from the specified file. | yii\helpers\BaseFileHelper |
loadMimeTypes() | Loads MIME types from the specified file. | yii\helpers\BaseFileHelper |
normalizeOptions() | yii\helpers\BaseFileHelper |
Constants
Constant | Value | Description | Defined By |
---|---|---|---|
PATTERN_CASE_INSENSITIVE | 32 | yii\helpers\BaseFileHelper | |
PATTERN_ENDSWITH | 4 | yii\helpers\BaseFileHelper | |
PATTERN_MUSTBEDIR | 8 | yii\helpers\BaseFileHelper | |
PATTERN_NEGATIVE | 16 | yii\helpers\BaseFileHelper | |
PATTERN_NODIR | 1 | yii\helpers\BaseFileHelper |
Property Details
The path (or alias) of a PHP file containing MIME aliases.
The path (or alias) of a PHP file containing MIME type information.
Method Details
Changes the Unix user and/or group ownership of a file or directory, and optionally the mode.
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. Note: On Windows, this function fails silently when applied on a regular file.
public static void changeOwnership ( $path, $ownership, $mode = null ) | ||
$path | string |
The path to the file or directory. |
$ownership | string|array|integer|null |
The user and/or group ownership for the file or directory.
When $ownership is a string, the format is 'user:group' where both are optional. E.g.
'user' or 'user:' will only change the user,
':group' will only change the group,
'user:group' will change both.
When $owners is an index array the format is [0 => user, 1 => group], e.g. |
$mode | integer|null |
The permission to be set for the file or directory.
If |
public static function changeOwnership($path, $ownership, $mode = null)
{
if (!file_exists((string)$path)) {
throw new InvalidArgumentException('Unable to change ownership, "' . $path . '" is not a file or directory.');
}
if (empty($ownership) && $ownership !== 0 && $mode === null) {
return;
}
$user = $group = null;
if (!empty($ownership) || $ownership === 0 || $ownership === '0') {
if (is_int($ownership)) {
$user = $ownership;
} elseif (is_string($ownership)) {
$ownerParts = explode(':', $ownership);
$user = $ownerParts[0];
if (count($ownerParts) > 1) {
$group = $ownerParts[1];
}
} elseif (is_array($ownership)) {
$ownershipIsIndexed = ArrayHelper::isIndexed($ownership);
$user = ArrayHelper::getValue($ownership, $ownershipIsIndexed ? 0 : 'user');
$group = ArrayHelper::getValue($ownership, $ownershipIsIndexed ? 1 : 'group');
} else {
throw new InvalidArgumentException('$ownership must be an integer, string, array, or null.');
}
}
if ($mode !== null) {
if (!is_int($mode)) {
throw new InvalidArgumentException('$mode must be an integer or null.');
}
if (!chmod($path, $mode)) {
throw new Exception('Unable to change mode of "' . $path . '" to "0' . decoct($mode) . '".');
}
}
if ($user !== null && $user !== '') {
if (is_numeric($user)) {
$user = (int) $user;
} elseif (!is_string($user)) {
throw new InvalidArgumentException('The user part of $ownership must be an integer, string, or null.');
}
if (!chown($path, $user)) {
throw new Exception('Unable to change user ownership of "' . $path . '" to "' . $user . '".');
}
}
if ($group !== null && $group !== '') {
if (is_numeric($group)) {
$group = (int) $group;
} elseif (!is_string($group)) {
throw new InvalidArgumentException('The group part of $ownership must be an integer, string or null.');
}
if (!chgrp($path, $group)) {
throw new Exception('Unable to change group ownership of "' . $path . '" to "' . $group . '".');
}
}
}
Copies a whole directory as another one.
The files and sub-directories will also be copied over.
public static void copyDirectory ( $src, $dst, $options = [] ) | ||
$src | string |
The source directory |
$dst | string |
The destination directory |
$options | array |
Options for directory copy. Valid options are:
|
throws | yii\base\InvalidArgumentException |
if unable to open directory |
---|
public static function copyDirectory($src, $dst, $options = [])
{
$src = static::normalizePath($src);
$dst = static::normalizePath($dst);
if ($src === $dst || strpos($dst, $src . DIRECTORY_SEPARATOR) === 0) {
throw new InvalidArgumentException('Trying to copy a directory to itself or a subdirectory.');
}
$dstExists = is_dir($dst);
if (!$dstExists && (!isset($options['copyEmptyDirectories']) || $options['copyEmptyDirectories'])) {
static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
$dstExists = true;
}
$handle = opendir($src);
if ($handle === false) {
throw new InvalidArgumentException("Unable to open directory: $src");
}
if (!isset($options['basePath'])) {
// this should be done only once
$options['basePath'] = realpath($src);
$options = static::normalizeOptions($options);
}
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$from = $src . DIRECTORY_SEPARATOR . $file;
$to = $dst . DIRECTORY_SEPARATOR . $file;
if (static::filterPath($from, $options)) {
if (isset($options['beforeCopy']) && !call_user_func($options['beforeCopy'], $from, $to)) {
continue;
}
if (is_file($from)) {
if (!$dstExists) {
// delay creation of destination directory until the first file is copied to avoid creating empty directories
static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
$dstExists = true;
}
copy($from, $to);
if (isset($options['fileMode'])) {
@chmod($to, $options['fileMode']);
}
} else {
// recursive copy, defaults to true
if (!isset($options['recursive']) || $options['recursive']) {
static::copyDirectory($from, $to, $options);
}
}
if (isset($options['afterCopy'])) {
call_user_func($options['afterCopy'], $from, $to);
}
}
}
closedir($handle);
}
Creates a new directory.
This method is similar to the PHP mkdir()
function except that
it uses chmod()
to set the permission of the created directory
in order to avoid the impact of the umask
setting.
public static boolean createDirectory ( $path, $mode = 0775, $recursive = true ) | ||
$path | string |
Path of the directory to be created. |
$mode | integer |
The permission to be set for the created directory. |
$recursive | boolean |
Whether to create parent directories if they do not exist. |
return | boolean |
Whether the directory is created successfully |
---|---|---|
throws | yii\base\Exception |
if the directory could not be created (i.e. php error due to parallel changes) |
public static function createDirectory($path, $mode = 0775, $recursive = true)
{
if (is_dir($path)) {
return true;
}
$parentDir = dirname($path);
// recurse if parent dir does not exist and we are not at the root of the file system.
if ($recursive && !is_dir($parentDir) && $parentDir !== $path) {
static::createDirectory($parentDir, $mode, true);
}
try {
if (!mkdir($path, $mode)) {
return false;
}
} catch (\Exception $e) {
if (!is_dir($path)) {// https://github.com/yiisoft/yii2/issues/9288
throw new \yii\base\Exception("Failed to create directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
}
}
try {
return chmod($path, $mode);
} catch (\Exception $e) {
throw new \yii\base\Exception("Failed to change permissions for directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
}
}
Checks if the given file path satisfies the filtering options.
public static boolean filterPath ( $path, $options ) | ||
$path | string |
The path of the file or directory to be checked |
$options | array |
The filtering options. See findFiles() for explanations of the supported options. |
return | boolean |
Whether the file or directory satisfies the filtering options. |
---|
public static function filterPath($path, $options)
{
if (isset($options['filter'])) {
$result = call_user_func($options['filter'], $path);
if (is_bool($result)) {
return $result;
}
}
if (empty($options['except']) && empty($options['only'])) {
return true;
}
$path = str_replace('\\', '/', $path);
if (
!empty($options['except'])
&& ($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null
) {
return $except['flags'] & self::PATTERN_NEGATIVE;
}
if (!empty($options['only']) && !is_dir($path)) {
return self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only']) !== null;
}
return true;
}
Returns the directories found under the specified directory and subdirectories.
public static array findDirectories ( $dir, $options = [] ) | ||
$dir | string |
The directory under which the files will be looked for. |
$options | array |
Options for directory searching. Valid options are:
|
return | array |
Directories found under the directory, in no particular order. Ordering depends on the files system used. |
---|---|---|
throws | yii\base\InvalidArgumentException |
if the dir is invalid. |
public static function findDirectories($dir, $options = [])
{
$dir = self::clearDir($dir);
$options = self::setBasePath($dir, $options);
$list = [];
$handle = self::openDir($dir);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($path) && static::filterPath($path, $options)) {
$list[] = $path;
if (!isset($options['recursive']) || $options['recursive']) {
$list = array_merge($list, static::findDirectories($path, $options));
}
}
}
closedir($handle);
return $list;
}
Returns the files found under the specified directory and subdirectories.
public static array findFiles ( $dir, $options = [] ) | ||
$dir | string |
The directory under which the files will be looked for. |
$options | array |
Options for file searching. Valid options are:
|
return | array |
Files found under the directory, in no particular order. Ordering depends on the files system used. |
---|---|---|
throws | yii\base\InvalidArgumentException |
if the dir is invalid. |
public static function findFiles($dir, $options = [])
{
$dir = self::clearDir($dir);
$options = self::setBasePath($dir, $options);
$list = [];
$handle = self::openDir($dir);
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (static::filterPath($path, $options)) {
if (is_file($path)) {
$list[] = $path;
} elseif (is_dir($path) && (!isset($options['recursive']) || $options['recursive'])) {
$list = array_merge($list, static::findFiles($path, $options));
}
}
}
closedir($handle);
return $list;
}
Determines the extensions by given MIME type.
This method will use a local map between extension names and MIME types.
public static array getExtensionsByMimeType ( $mimeType, $magicFile = null ) | ||
$mimeType | string |
File MIME type. |
$magicFile | string|null |
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used. |
return | array |
The extensions corresponding to the specified MIME type |
---|
public static function getExtensionsByMimeType($mimeType, $magicFile = null)
{
$aliases = static::loadMimeAliases(static::$mimeAliasesFile);
if (isset($aliases[$mimeType])) {
$mimeType = $aliases[$mimeType];
}
$mimeTypes = static::loadMimeTypes($magicFile);
return array_keys($mimeTypes, mb_strtolower($mimeType, 'UTF-8'), true);
}
Determines the MIME type of the specified file.
This method will first try to determine the MIME type based on
finfo_open. If the fileinfo
extension is not installed,
it will fall back to getMimeTypeByExtension() when $checkExtension
is true.
public static string|null getMimeType ( $file, $magicFile = null, $checkExtension = true ) | ||
$file | string |
The file name. |
$magicFile | string|null |
Name of the optional magic database file (or alias), usually something like |
$checkExtension | boolean |
Whether to use the file extension to determine the MIME type in case
|
return | string|null |
The MIME type (e.g. |
---|---|---|
throws | yii\base\InvalidConfigException |
when the |
public static function getMimeType($file, $magicFile = null, $checkExtension = true)
{
if ($magicFile !== null) {
$magicFile = Yii::getAlias($magicFile);
}
if (!extension_loaded('fileinfo')) {
if ($checkExtension) {
return static::getMimeTypeByExtension($file, $magicFile);
}
throw new InvalidConfigException('The fileinfo PHP extension is not installed.');
}
$info = finfo_open(FILEINFO_MIME_TYPE, $magicFile);
if ($info) {
$result = finfo_file($info, $file);
finfo_close($info);
if ($result !== false) {
return $result;
}
}
return $checkExtension ? static::getMimeTypeByExtension($file, $magicFile) : null;
}
Determines the MIME type based on the extension name of the specified file.
This method will use a local map between extension names and MIME types.
public static string|null getMimeTypeByExtension ( $file, $magicFile = null ) | ||
$file | string |
The file name. |
$magicFile | string|null |
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used. |
return | string|null |
The MIME type. Null is returned if the MIME type cannot be determined. |
---|
public static function getMimeTypeByExtension($file, $magicFile = null)
{
$mimeTypes = static::loadMimeTypes($magicFile);
if (($ext = pathinfo($file, PATHINFO_EXTENSION)) !== '') {
$ext = strtolower($ext);
if (isset($mimeTypes[$ext])) {
return $mimeTypes[$ext];
}
}
return null;
}
Loads MIME aliases from the specified file.
protected static array loadMimeAliases ( $aliasesFile ) | ||
$aliasesFile | string|null |
The path (or alias) of the file that contains MIME type aliases. If this is not set, the file specified by $mimeAliasesFile will be used. |
return | array |
The mapping from file extensions to MIME types |
---|
protected static function loadMimeAliases($aliasesFile)
{
if ($aliasesFile === null) {
$aliasesFile = static::$mimeAliasesFile;
}
$aliasesFile = Yii::getAlias($aliasesFile);
if (!isset(self::$_mimeAliases[$aliasesFile])) {
self::$_mimeAliases[$aliasesFile] = require $aliasesFile;
}
return self::$_mimeAliases[$aliasesFile];
}
Loads MIME types from the specified file.
protected static array loadMimeTypes ( $magicFile ) | ||
$magicFile | string|null |
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used. |
return | array |
The mapping from file extensions to MIME types |
---|
protected static function loadMimeTypes($magicFile)
{
if ($magicFile === null) {
$magicFile = static::$mimeMagicFile;
}
$magicFile = Yii::getAlias($magicFile);
if (!isset(self::$_mimeTypes[$magicFile])) {
self::$_mimeTypes[$magicFile] = require $magicFile;
}
return self::$_mimeTypes[$magicFile];
}
Returns the localized version of a specified file.
The searching is based on the specified language code. In particular, a file with the same name will be looked for under the subdirectory whose name is the same as the language code. For example, given the file "path/to/view.php" and language code "zh-CN", the localized file will be looked for as "path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is "zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.
If the target and the source language codes are the same, the original file will be returned.
public static string localize ( $file, $language = null, $sourceLanguage = null ) | ||
$file | string |
The original file |
$language | string|null |
The target language that the file should be localized to. If not set, the value of yii\base\Application::$language will be used. |
$sourceLanguage | string|null |
The language that the original file is in. If not set, the value of yii\base\Application::$sourceLanguage will be used. |
return | string |
The matching localized file, or the original file if the localized version is not found. If the target and the source language codes are the same, the original file will be returned. |
---|
public static function localize($file, $language = null, $sourceLanguage = null)
{
if ($language === null) {
$language = Yii::$app->language;
}
if ($sourceLanguage === null) {
$sourceLanguage = Yii::$app->sourceLanguage;
}
if ($language === $sourceLanguage) {
return $file;
}
$desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
if (is_file($desiredFile)) {
return $desiredFile;
}
$language = substr($language, 0, 2);
if ($language === $sourceLanguage) {
return $file;
}
$desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
return is_file($desiredFile) ? $desiredFile : $file;
}
protected static array normalizeOptions ( array $options ) | ||
$options | array |
Raw options |
return | array |
Normalized options |
---|
protected static function normalizeOptions(array $options)
{
if (!array_key_exists('caseSensitive', $options)) {
$options['caseSensitive'] = true;
}
if (isset($options['except'])) {
foreach ($options['except'] as $key => $value) {
if (is_string($value)) {
$options['except'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
}
}
}
if (isset($options['only'])) {
foreach ($options['only'] as $key => $value) {
if (is_string($value)) {
$options['only'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
}
}
}
return $options;
}
Normalizes a file/directory path.
The normalization does the following work:
- Convert all directory separators into
DIRECTORY_SEPARATOR
(e.g. "\a/b\c" becomes "/a/b/c") - Remove trailing directory separators (e.g. "/a/b/c/" becomes "/a/b/c")
- Turn multiple consecutive slashes into a single one (e.g. "/a///b/c" becomes "/a/b/c")
- Remove ".." and "." based on their meanings (e.g. "/a/./b/../c" becomes "/a/c")
Note: For registered stream wrappers, the consecutive slashes rule and ".."/"." translations are skipped.
public static string normalizePath ( $path, $ds = DIRECTORY_SEPARATOR ) | ||
$path | string |
The file/directory path to be normalized |
$ds | string |
The directory separator to be used in the normalized result. Defaults to |
return | string |
The normalized file/directory path |
---|
public static function normalizePath($path, $ds = DIRECTORY_SEPARATOR)
{
$path = rtrim(strtr($path, '/\\', $ds . $ds), $ds);
if (strpos($ds . $path, "{$ds}.") === false && strpos($path, "{$ds}{$ds}") === false) {
return $path;
}
// fix #17235 stream wrappers
foreach (stream_get_wrappers() as $protocol) {
if (strpos($path, "{$protocol}://") === 0) {
return $path;
}
}
// the path may contain ".", ".." or double slashes, need to clean them up
if (strpos($path, "{$ds}{$ds}") === 0 && $ds == '\\') {
$parts = [$ds];
} else {
$parts = [];
}
foreach (explode($ds, $path) as $part) {
if ($part === '..' && !empty($parts) && end($parts) !== '..') {
array_pop($parts);
} elseif ($part === '.' || $part === '' && !empty($parts)) {
continue;
} else {
$parts[] = $part;
}
}
$path = implode($ds, $parts);
return $path === '' ? '.' : $path;
}
Removes a directory (and all its content) recursively.
public static void removeDirectory ( $dir, $options = [] ) | ||
$dir | string |
The directory to be deleted recursively. |
$options | array |
Options for directory remove. Valid options are:
|
throws | yii\base\ErrorException |
in case of failure |
---|
public static function removeDirectory($dir, $options = [])
{
if (!is_dir($dir)) {
return;
}
if (!empty($options['traverseSymlinks']) || !is_link($dir)) {
if (!($handle = opendir($dir))) {
return;
}
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') {
continue;
}
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($path)) {
static::removeDirectory($path, $options);
} else {
static::unlink($path);
}
}
closedir($handle);
}
if (is_link($dir)) {
static::unlink($dir);
} else {
rmdir($dir);
}
}
Removes a file or symlink in a cross-platform way
public static boolean unlink ( $path ) | ||
$path | string |
public static function unlink($path)
{
$isWindows = DIRECTORY_SEPARATOR === '\\';
if (!$isWindows) {
return unlink($path);
}
if (is_link($path) && is_dir($path)) {
return rmdir($path);
}
try {
return unlink($path);
} catch (ErrorException $e) {
// last resort measure for Windows
if (is_dir($path) && count(static::findFiles($path)) !== 0) {
return false;
}
if (function_exists('exec') && file_exists($path)) {
exec('DEL /F/Q ' . escapeshellarg($path));
return !file_exists($path);
}
return false;
}
}