A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.yiiframework.com/doc/api/2.0/yii-helpers-filehelper below:

FileHelper, yii\helpers\FileHelper | API Documentation for Yii 2.0

Class yii\helpers\FileHelper

File system helper.

Method Details

Hide inherited methods

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.

Source code

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

            
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

Source code

                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'])) {
        
        $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) {
                    
                    static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
                    $dstExists = true;
                }
                copy($from, $to);
                if (isset($options['fileMode'])) {
                    @chmod($to, $options['fileMode']);
                }
            } else {
                
                if (!isset($options['recursive']) || $options['recursive']) {
                    static::copyDirectory($from, $to, $options);
                }
            }
            if (isset($options['afterCopy'])) {
                call_user_func($options['afterCopy'], $from, $to);
            }
        }
    }
    closedir($handle);
}

            

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)

Source code

                public static function createDirectory($path, $mode = 0775, $recursive = true)
{
    if (is_dir($path)) {
        return true;
    }
    $parentDir = dirname($path);
    
    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)) {
            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);
    }
}

            
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.

Source code

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

            
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.

Source code

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

            
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.

Source code

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

            
public static string|null getExtensionByMimeType ( $mimeType, $preferShort false, $magicFile null ) $mimeType string

File MIME type.

$preferShort boolean

Return an extension with a maximum of 3 characters.

$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 extensions corresponding to the specified MIME type

Source code

                public static function getExtensionByMimeType($mimeType, $preferShort = false, $magicFile = null)
{
    $aliases = static::loadMimeAliases(static::$mimeAliasesFile);
    if (isset($aliases[$mimeType])) {
        $mimeType = $aliases[$mimeType];
    }
    $mimeExtensions = static::loadMimeExtensions($magicFile);
    if (!array_key_exists($mimeType, $mimeExtensions)) {
        return null;
    }
    $extensions = $mimeExtensions[$mimeType];
    if (is_array($extensions)) {
        if ($preferShort) {
            foreach ($extensions as $extension) {
                if (mb_strlen($extension, 'UTF-8') <= 3) {
                    return $extension;
                }
            }
        }
        return $extensions[0];
    } else {
        return $extensions;
    }
}

            
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

Source code

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

            
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.

Source code

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

            
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.

Source code

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

            
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

Source code

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

            
protected static array loadMimeExtensions ( $extensionsFile ) $extensionsFile 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

Source code

                protected static function loadMimeExtensions($extensionsFile)
{
    if ($extensionsFile === null) {
        $extensionsFile = static::$mimeExtensionsFile;
    }
    $extensionsFile = Yii::getAlias($extensionsFile);
    if (!isset(self::$_mimeExtensions[$extensionsFile])) {
        self::$_mimeExtensions[$extensionsFile] = require $extensionsFile;
    }
    return self::$_mimeExtensions[$extensionsFile];
}

            
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

Source code

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

            

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.

Source code

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

            

Source code

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

            

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

Normalizes a file/directory path.

The normalization does the following work:

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

Source code

                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;
    }
    
    foreach (stream_get_wrappers() as $protocol) {
        if (strpos($path, "{$protocol}://") === 0) {
            return $path;
        }
    }
    
    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;
}

            
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

Source code

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

            

Source code

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

            

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4