Class luya\helpers\FileHelper

Inheritanceluya\helpers\FileHelper » luya\yii\helpers\FileHelper » yii\helpers\BaseFileHelper
Available since version1.0.0
Source Code https://github.com/luyadev/luya/blob/master/core/helpers/FileHelper.php

Helper methods when dealing with Files.

Public Properties

Hide inherited 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

Hide inherited 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
classInfo() Provide class informations from a file path or file content. luya\yii\helpers\FileHelper
copyDirectory() Copies a whole directory as another one. yii\helpers\BaseFileHelper
createDirectory() Creates a new directory. yii\helpers\BaseFileHelper
ensureExtension() Append a file extension to a path/file if there is no or an empty extension provided, this helper methods is used to make sure the right extension existing on files. luya\yii\helpers\FileHelper
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
getFileContent() Basic helper to retreive the content of a file and catched exception. The filename will auto alias encode by Yii::getAlias function. luya\yii\helpers\FileHelper
getFileInfo() Get extension and name from a file for the provided source/path of the file. luya\yii\helpers\FileHelper
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
hashName() Create a unique hash name from a given file. luya\yii\helpers\FileHelper
humanReadableFilesize() Generate a human readable size informations from provided Byte/s size luya\yii\helpers\FileHelper
localize() Returns the localized version of a specified file. yii\helpers\BaseFileHelper
md5sum() Generate a md5 hash of a file. This is eqauls to md5sum command luya\yii\helpers\FileHelper
normalizePath() Normalizes a file/directory path. yii\helpers\BaseFileHelper
removeDirectory() Removes a directory (and all its content) recursively. yii\helpers\BaseFileHelper
unlink() Unlink a file, which handles symlinks. luya\yii\helpers\FileHelper
writeFile() Basic helper method to write files with exception capture. The fileName will auto wrapped trough the Yii::getAlias function. luya\yii\helpers\FileHelper

Protected Methods

Hide inherited 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

Hide inherited 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

Method Details

Hide inherited methods

changeOwnership() public static method (available since version 2.0.43)

Defined in: yii\helpers\BaseFileHelper::changeOwnership()

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. [$myUser, $myGroup]. It is also possible to pass an associative array, e.g. ['user' => $myUser, 'group' => $myGroup]. In case $owners is an integer it will be used as user id. If null, an empty array or an empty string is passed, the ownership will not be changed.

$mode integer|null

The permission to be set for the file or directory. If null is passed, the mode will not be changed.

                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 . '".');
        }
    }
}

            
classInfo() public static method

Defined in: luya\yii\helpers\FileHelper::classInfo()

Provide class informations from a file path or file content.

This is used when working with file paths from composer, in order to detect class and namespace from a given file.

public static array classInfo ( $file )
$file string

The file path to the class into order to get infos from, could also be the content directly from a given file.

return array

If the given filepath is a file, it will return an array with the keys:

  • namespace: the namespace of the file, if false no namespace could have been determined.
  • class: the class name of the file, if false no class could have been determined.

                public static function classInfo($file)
{
    if (is_file($file)) {
        $phpCode = file_get_contents($file);
    } else {
        $phpCode = $file;
    }
    $namespace = false;
    if (preg_match('/^namespace\s+(.+?);(\s+|\r\n)?$/sm', $phpCode, $results)) {
        $namespace = $results[1];
    }
    $classes = self::classNameByTokens($phpCode);
    return ['namespace' => $namespace, 'class' => end($classes)];
}

            
copyDirectory() public static method

Defined in: yii\helpers\BaseFileHelper::copyDirectory()

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:

  • dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
  • fileMode: integer, the permission to be set for newly copied files. Defaults to the current environment setting.
  • filter: callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path), where $path refers the full path to be filtered. The callback can return one of the following values:

    • true: the directory or file will be copied (the "only" and "except" options will be ignored)
    • false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
    • null: the "only" and "except" options will determine whether the directory or file should be copied
  • only: array, list of patterns that the file paths should match if they want to be copied. A path matches a pattern if it contains the pattern string at its end. For example, '.php' matches all file paths ending with '.php'. Note, the '/' characters in a pattern matches both '/' and '\' in the paths. If a file path matches a pattern in both "only" and "except", it will NOT be copied.
  • except: array, list of patterns that the files or directories should match if they want to be excluded from being copied. A path matches a pattern if it contains the pattern string at its end. Patterns ending with '/' apply to directory paths only, and patterns not ending with '/' apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b'; and '.svn/' matches directory paths ending with '.svn'. Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
  • caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
  • recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true.
  • beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file. If the callback returns false, the copy operation for the sub-directory or file will be cancelled. The signature of the callback should be: function ($from, $to), where $from is the sub-directory or file to be copied from, while $to is the copy target.
  • afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied. The signature of the callback should be: function ($from, $to), where $from is the sub-directory or file copied from, while $to is the copy target.
  • copyEmptyDirectories: boolean, whether to copy empty directories. Set this to false to avoid creating directories that do not contain files. This affects directories that do not contain files initially as well as directories that do not contain files at the target destination because files have been filtered via only or except. Defaults to true. This option is available since version 2.0.12. Before 2.0.12 empty directories are always copied.
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);
}

            
createDirectory() public static method

Defined in: yii\helpers\BaseFileHelper::createDirectory()

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);
    }
}

            
ensureExtension() public static method

Defined in: luya\yii\helpers\FileHelper::ensureExtension()

Append a file extension to a path/file if there is no or an empty extension provided, this helper methods is used to make sure the right extension existing on files.

public static string ensureExtension ( $file, $extension )
$file string

The file where extension should be append if not existing

$extension string
return string

The ensured file/path with extension

                public static function ensureExtension($file, $extension)
{
    $info = pathinfo($file);
    if (!isset($info['extension']) || empty($info['extension'])) {
        $file = rtrim($file, '.') . '.' . $extension;
    }
    return $file;
}

            
filterPath() public static method

Defined in: yii\helpers\BaseFileHelper::filterPath()

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;
}

            
findDirectories() public static method (available since version 2.0.14)

Defined in: yii\helpers\BaseFileHelper::findDirectories()

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:

  • filter: callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function (string $path): bool, where $path refers the full path to be filtered. The callback can return one of the following values:

    • true: the directory will be returned
    • false: the directory will NOT be returned
  • recursive: boolean, whether the files under the subdirectories should also be looked for. Defaults to true. See findFiles() for more options.

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;
}

            
findFiles() public static method

Defined in: yii\helpers\BaseFileHelper::findFiles()

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:

  • filter: callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path), where $path refers the full path to be filtered. The callback can return one of the following values:

    • true: the directory or file will be returned (the only and except options will be ignored)
    • false: the directory or file will NOT be returned (the only and except options will be ignored)
    • null: the only and except options will determine whether the directory or file should be returned
  • except: array, list of patterns excluding from the results matching file or directory paths. Patterns ending with slash ('/') apply to directory paths only, and patterns not ending with '/' apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b'; and .svn/ matches directory paths ending with .svn. If the pattern does not contain a slash (/), it is treated as a shell glob pattern and checked for a match against the pathname relative to $dir. Otherwise, the pattern is treated as a shell glob suitable for consumption by fnmatch(3) with the FNM_PATHNAME flag: wildcards in the pattern will not match a / in the pathname. For example, views/*.php matches views/index.php but not views/controller/index.php. A leading slash matches the beginning of the pathname. For example, /*.php matches index.php but not views/start/index.php. An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources. Put a backslash (\) in front of the first ! for patterns that begin with a literal !, for example, \!important!.txt. Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
  • only: array, list of patterns that the file paths should match if they are to be returned. Directory paths are not checked against them. Same pattern matching rules as in the except option are used. If a file path matches a pattern in both only and except, it will NOT be returned.
  • caseSensitive: boolean, whether patterns specified at only or except should be case sensitive. Defaults to true.
  • recursive: boolean, whether the files under the subdirectories should also be looked for. Defaults to true.
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;
}

            
getExtensionsByMimeType() public static method

Defined in: yii\helpers\BaseFileHelper::getExtensionsByMimeType()

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);
}

            
getFileContent() public static method

Defined in: luya\yii\helpers\FileHelper::getFileContent()

Basic helper to retreive the content of a file and catched exception. The filename will auto alias encode by Yii::getAlias function.

public static string|boolean getFileContent ( $fileName )
$fileName string

The path to the file to get the content

                public static function getFileContent($fileName)
{
    try {
        return file_get_contents(Yii::getAlias($fileName));
    } catch (Exception $error) {
        return false;
    }
}

            
getFileInfo() public static method

Defined in: luya\yii\helpers\FileHelper::getFileInfo()

Get extension and name from a file for the provided source/path of the file.

public static object getFileInfo ( $sourceFile )
$sourceFile string

The path of the file

return object

With extension and name keys.

                public static function getFileInfo($sourceFile)
{
    // pathinfo always returns an array event the path does not exists
    $path = pathinfo($sourceFile);
    return (object) [
        'extension' => !empty($path['extension']) ? mb_strtolower($path['extension'], 'UTF-8') : false,
        'name' => !empty($path['filename']) ? $path['filename'] : false,
        'source' => $sourceFile,
        'sourceFilename' => !empty($path['filename']) ? $path['dirname'] . DIRECTORY_SEPARATOR . $path['filename'] : false,
    ];
}

            
getMimeType() public static method

Defined in: yii\helpers\BaseFileHelper::getMimeType()

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 /path/to/magic.mime. This will be passed as the second parameter to finfo_open() when the fileinfo extension is installed. If the MIME type is being determined based via getMimeTypeByExtension() and this is null, it will use the file specified by $mimeMagicFile.

$checkExtension boolean

Whether to use the file extension to determine the MIME type in case finfo_open() cannot determine it.

return string|null

The MIME type (e.g. text/plain). Null is returned if the MIME type cannot be determined.

throws yii\base\InvalidConfigException

when the fileinfo PHP extension is not installed and $checkExtension is false.

                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;
}

            
getMimeTypeByExtension() public static method

Defined in: yii\helpers\BaseFileHelper::getMimeTypeByExtension()

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;
}

            
hashName() public static method

Defined in: luya\yii\helpers\FileHelper::hashName()

Create a unique hash name from a given file.

Warning Because PHP's integer type is signed many crc32 checksums will result in negative integers on 32bit platforms. On 64bit installations all crc32() results will be positive integers though. So you need to use the "%u" formatter of sprintf() or printf() to get the string representation of the unsigned crc32() checksum in decimal format.

public static string hashName ( $fileName )
$fileName string

The file name which should be hashed

                public static function hashName($fileName)
{
    return sprintf('%s', hash('crc32b', uniqid($fileName, true)));
}

            
humanReadableFilesize() public static method

Defined in: luya\yii\helpers\FileHelper::humanReadableFilesize()

Generate a human readable size informations from provided Byte/s size

public static string humanReadableFilesize ( $size )
$size integer

The size to convert in Byte

return string

The readable size definition

                public static function humanReadableFilesize($size)
{
    $mod = 1024;
    $units = explode(' ', 'B KB MB GB TB PB');
    for ($i = 0; $size > $mod; ++$i) {
        $size /= $mod;
    }
    return round($size, 2).' '.$units[$i];
}

            
loadMimeAliases() protected static method (available since version 2.0.14)

Defined in: yii\helpers\BaseFileHelper::loadMimeAliases()

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];
}

            
loadMimeTypes() protected static method

Defined in: yii\helpers\BaseFileHelper::loadMimeTypes()

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];
}

            
localize() public static method

Defined in: yii\helpers\BaseFileHelper::localize()

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;
}

            
md5sum() public static method

Defined in: luya\yii\helpers\FileHelper::md5sum()

Generate a md5 hash of a file. This is eqauls to md5sum command

public static false|string md5sum ( $sourceFile )
$sourceFile string

The path to the file

return false|string

Returns false or the md5 hash of this file

                public static function md5sum($sourceFile)
{
    return file_exists($sourceFile) ? hash_file('md5', $sourceFile) : false;
}

            
normalizeOptions() protected static method (available since version 2.0.12)
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;
}

            
normalizePath() public static method

Defined in: yii\helpers\BaseFileHelper::normalizePath()

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 DIRECTORY_SEPARATOR.

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;
}

            
removeDirectory() public static method

Defined in: yii\helpers\BaseFileHelper::removeDirectory()

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:

  • traverseSymlinks: boolean, whether symlinks to the directories should be traversed too. Defaults to false, meaning the content of the symlinked directory would not be deleted. Only symlink would be removed in that default case.
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);
    }
}

            
unlink() public static method

Defined in: luya\yii\helpers\FileHelper::unlink()

Unlink a file, which handles symlinks.

public static boolean unlink ( $file )
$file string

The file path to the file to delete.

return boolean

Whether the file has been removed or not.

writeFile() public static method

Defined in: luya\yii\helpers\FileHelper::writeFile()

Basic helper method to write files with exception capture. The fileName will auto wrapped trough the Yii::getAlias function.

public static boolean writeFile ( $fileName, $content )
$fileName string

The path to the file with file name

$content string

The content to store in this File

                public static function writeFile($fileName, $content)
{
    try {
        $response = file_put_contents(Yii::getAlias($fileName), $content);
        if ($response === false) {
            return false;
        }
    } catch (Exception $error) {
        return false;
    }
    return true;
}