Completed
Push — master ( 1501c6...5a8c3d )
by Carsten
12:28
created

BaseFileHelper::filterPath()   D

Complexity

Conditions 10
Paths 17

Size

Total Lines 32
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 10

Importance

Changes 0
Metric Value
dl 0
loc 32
ccs 16
cts 16
cp 1
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 16
nc 17
nop 2
crap 10

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\helpers;
9
10
use Yii;
11
use yii\base\ErrorException;
12
use yii\base\InvalidConfigException;
13
use yii\base\InvalidParamException;
14
15
/**
16
 * BaseFileHelper provides concrete implementation for [[FileHelper]].
17
 *
18
 * Do not use BaseFileHelper. Use [[FileHelper]] instead.
19
 *
20
 * @author Qiang Xue <[email protected]>
21
 * @author Alex Makarov <[email protected]>
22
 * @since 2.0
23
 */
24
class BaseFileHelper
25
{
26
    const PATTERN_NODIR = 1;
27
    const PATTERN_ENDSWITH = 4;
28
    const PATTERN_MUSTBEDIR = 8;
29
    const PATTERN_NEGATIVE = 16;
30
    const PATTERN_CASE_INSENSITIVE = 32;
31
32
    /**
33
     * @var string the path (or alias) of a PHP file containing MIME type information.
34
     */
35
    public static $mimeMagicFile = '@yii/helpers/mimeTypes.php';
36
37
38
    /**
39
     * Normalizes a file/directory path.
40
     *
41
     * The normalization does the following work:
42
     *
43
     * - Convert all directory separators into `DIRECTORY_SEPARATOR` (e.g. "\a/b\c" becomes "/a/b/c")
44
     * - Remove trailing directory separators (e.g. "/a/b/c/" becomes "/a/b/c")
45
     * - Turn multiple consecutive slashes into a single one (e.g. "/a///b/c" becomes "/a/b/c")
46
     * - Remove ".." and "." based on their meanings (e.g. "/a/./b/../c" becomes "/a/c")
47
     *
48
     * @param string $path the file/directory path to be normalized
49
     * @param string $ds the directory separator to be used in the normalized result. Defaults to `DIRECTORY_SEPARATOR`.
50
     * @return string the normalized file/directory path
51
     */
52 34
    public static function normalizePath($path, $ds = DIRECTORY_SEPARATOR)
53
    {
54 34
        $path = rtrim(strtr($path, '/\\', $ds . $ds), $ds);
55 34
        if (strpos($ds . $path, "{$ds}.") === false && strpos($path, "{$ds}{$ds}") === false) {
56 33
            return $path;
57
        }
58
        // the path may contain ".", ".." or double slashes, need to clean them up
59 1
        $parts = [];
60 1
        foreach (explode($ds, $path) as $part) {
61 1
            if ($part === '..' && !empty($parts) && end($parts) !== '..') {
62 1
                array_pop($parts);
63 1
            } elseif ($part === '.' || $part === '' && !empty($parts)) {
64 1
                continue;
65
            } else {
66 1
                $parts[] = $part;
67
            }
68
        }
69 1
        $path = implode($ds, $parts);
70 1
        return $path === '' ? '.' : $path;
71
    }
72
73
    /**
74
     * Returns the localized version of a specified file.
75
     *
76
     * The searching is based on the specified language code. In particular,
77
     * a file with the same name will be looked for under the subdirectory
78
     * whose name is the same as the language code. For example, given the file "path/to/view.php"
79
     * and language code "zh-CN", the localized file will be looked for as
80
     * "path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is
81
     * "zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.
82
     *
83
     * If the target and the source language codes are the same,
84
     * the original file will be returned.
85
     *
86
     * @param string $file the original file
87
     * @param string $language the target language that the file should be localized to.
88
     * If not set, the value of [[\yii\base\Application::language]] will be used.
89
     * @param string $sourceLanguage the language that the original file is in.
90
     * If not set, the value of [[\yii\base\Application::sourceLanguage]] will be used.
91
     * @return string the matching localized file, or the original file if the localized version is not found.
92
     * If the target and the source language codes are the same, the original file will be returned.
93
     */
94 71
    public static function localize($file, $language = null, $sourceLanguage = null)
95
    {
96 71
        if ($language === null) {
97 70
            $language = Yii::$app->language;
98
        }
99 71
        if ($sourceLanguage === null) {
100 70
            $sourceLanguage = Yii::$app->sourceLanguage;
101
        }
102 71
        if ($language === $sourceLanguage) {
103 71
            return $file;
104
        }
105 1
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
106 1
        if (is_file($desiredFile)) {
107 1
            return $desiredFile;
108
        }
109
110
        $language = substr($language, 0, 2);
111
        if ($language === $sourceLanguage) {
112
            return $file;
113
        }
114
        $desiredFile = dirname($file) . DIRECTORY_SEPARATOR . $language . DIRECTORY_SEPARATOR . basename($file);
115
116
        return is_file($desiredFile) ? $desiredFile : $file;
117
    }
118
119
    /**
120
     * Determines the MIME type of the specified file.
121
     * This method will first try to determine the MIME type based on
122
     * [finfo_open](http://php.net/manual/en/function.finfo-open.php). If the `fileinfo` extension is not installed,
123
     * it will fall back to [[getMimeTypeByExtension()]] when `$checkExtension` is true.
124
     * @param string $file the file name.
125
     * @param string $magicFile name of the optional magic database file (or alias), usually something like `/path/to/magic.mime`.
126
     * This will be passed as the second parameter to [finfo_open()](http://php.net/manual/en/function.finfo-open.php)
127
     * when the `fileinfo` extension is installed. If the MIME type is being determined based via [[getMimeTypeByExtension()]]
128
     * and this is null, it will use the file specified by [[mimeMagicFile]].
129
     * @param bool $checkExtension whether to use the file extension to determine the MIME type in case
130
     * `finfo_open()` cannot determine it.
131
     * @return string the MIME type (e.g. `text/plain`). Null is returned if the MIME type cannot be determined.
132
     * @throws InvalidConfigException when the `fileinfo` PHP extension is not installed and `$checkExtension` is `false`.
133
     */
134 12
    public static function getMimeType($file, $magicFile = null, $checkExtension = true)
135
    {
136 12
        if ($magicFile !== null) {
137
            $magicFile = Yii::getAlias($magicFile);
138
        }
139 12
        if (!extension_loaded('fileinfo')) {
140
            if ($checkExtension) {
141
                return static::getMimeTypeByExtension($file, $magicFile);
0 ignored issues
show
Bug introduced by
It seems like $magicFile defined by \Yii::getAlias($magicFile) on line 137 can also be of type boolean; however, yii\helpers\BaseFileHelp...etMimeTypeByExtension() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
142
            }
143
144
            throw new InvalidConfigException('The fileinfo PHP extension is not installed.');
145
        }
146 12
        $info = finfo_open(FILEINFO_MIME_TYPE, $magicFile);
147
148 12
        if ($info) {
149 12
            $result = finfo_file($info, $file);
150 12
            finfo_close($info);
151
152 12
            if ($result !== false) {
153 12
                return $result;
154
            }
155
        }
156
157
        return $checkExtension ? static::getMimeTypeByExtension($file, $magicFile) : null;
0 ignored issues
show
Bug introduced by
It seems like $magicFile defined by \Yii::getAlias($magicFile) on line 137 can also be of type boolean; however, yii\helpers\BaseFileHelp...etMimeTypeByExtension() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
158
    }
159
160
    /**
161
     * Determines the MIME type based on the extension name of the specified file.
162
     * This method will use a local map between extension names and MIME types.
163
     * @param string $file the file name.
164
     * @param string $magicFile the path (or alias) of the file that contains all available MIME type information.
165
     * If this is not set, the file specified by [[mimeMagicFile]] will be used.
166
     * @return string|null the MIME type. Null is returned if the MIME type cannot be determined.
167
     */
168 8
    public static function getMimeTypeByExtension($file, $magicFile = null)
169
    {
170 8
        $mimeTypes = static::loadMimeTypes($magicFile);
171
172 8
        if (($ext = pathinfo($file, PATHINFO_EXTENSION)) !== '') {
173 8
            $ext = strtolower($ext);
174 8
            if (isset($mimeTypes[$ext])) {
175 8
                return $mimeTypes[$ext];
176
            }
177
        }
178
179 1
        return null;
180
    }
181
182
    /**
183
     * Determines the extensions by given MIME type.
184
     * This method will use a local map between extension names and MIME types.
185
     * @param string $mimeType file MIME type.
186
     * @param string $magicFile the path (or alias) of the file that contains all available MIME type information.
187
     * If this is not set, the file specified by [[mimeMagicFile]] will be used.
188
     * @return array the extensions corresponding to the specified MIME type
189
     */
190
    public static function getExtensionsByMimeType($mimeType, $magicFile = null)
191
    {
192
        $mimeTypes = static::loadMimeTypes($magicFile);
193
        return array_keys($mimeTypes, mb_strtolower($mimeType, 'UTF-8'), true);
194
    }
195
196
    private static $_mimeTypes = [];
197
198
    /**
199
     * Loads MIME types from the specified file.
200
     * @param string $magicFile the path (or alias) of the file that contains all available MIME type information.
201
     * If this is not set, the file specified by [[mimeMagicFile]] will be used.
202
     * @return array the mapping from file extensions to MIME types
203
     */
204 8
    protected static function loadMimeTypes($magicFile)
205
    {
206 8
        if ($magicFile === null) {
207 8
            $magicFile = static::$mimeMagicFile;
208
        }
209 8
        $magicFile = Yii::getAlias($magicFile);
210 8
        if (!isset(self::$_mimeTypes[$magicFile])) {
211 1
            self::$_mimeTypes[$magicFile] = require $magicFile;
212
        }
213
214 8
        return self::$_mimeTypes[$magicFile];
215
    }
216
217
    /**
218
     * Copies a whole directory as another one.
219
     * The files and sub-directories will also be copied over.
220
     * @param string $src the source directory
221
     * @param string $dst the destination directory
222
     * @param array $options options for directory copy. Valid options are:
223
     *
224
     * - dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
225
     * - fileMode:  integer, the permission to be set for newly copied files. Defaults to the current environment setting.
226
     * - filter: callback, a PHP callback that is called for each directory or file.
227
     *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
228
     *   The callback can return one of the following values:
229
     *
230
     *   * true: the directory or file will be copied (the "only" and "except" options will be ignored)
231
     *   * false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
232
     *   * null: the "only" and "except" options will determine whether the directory or file should be copied
233
     *
234
     * - only: array, list of patterns that the file paths should match if they want to be copied.
235
     *   A path matches a pattern if it contains the pattern string at its end.
236
     *   For example, '.php' matches all file paths ending with '.php'.
237
     *   Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
238
     *   If a file path matches a pattern in both "only" and "except", it will NOT be copied.
239
     * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
240
     *   A path matches a pattern if it contains the pattern string at its end.
241
     *   Patterns ending with '/' apply to directory paths only, and patterns not ending with '/'
242
     *   apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
243
     *   and '.svn/' matches directory paths ending with '.svn'. Note, the '/' characters in a pattern matches
244
     *   both '/' and '\' in the paths.
245
     * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
246
     * - recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true.
247
     * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
248
     *   If the callback returns false, the copy operation for the sub-directory or file will be cancelled.
249
     *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
250
     *   file to be copied from, while `$to` is the copy target.
251
     * - afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied.
252
     *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
253
     *   file copied from, while `$to` is the copy target.
254
     * - copyEmptyDirectories: boolean, whether to copy empty directories. Set this to false to avoid creating directories
255
     *   that do not contain files. This affects directories that do not contain files initially as well as directories that
256
     *   do not contain files at the target destination because files have been filtered via `only` or `except`.
257
     *   Defaults to true. This option is available since version 2.0.12. Before 2.0.12 empty directories are always copied.
258
     * @throws \yii\base\InvalidParamException if unable to open directory
259
     */
260 17
    public static function copyDirectory($src, $dst, $options = [])
261
    {
262 17
        $src = static::normalizePath($src);
263 17
        $dst = static::normalizePath($dst);
264
265 17
        if ($src === $dst || strpos($dst, $src . DIRECTORY_SEPARATOR) === 0) {
266 2
            throw new InvalidParamException('Trying to copy a directory to itself or a subdirectory.');
267
        }
268 15
        $dstExists = is_dir($dst);
269 15
        if (!$dstExists && (!isset($options['copyEmptyDirectories']) || $options['copyEmptyDirectories'])) {
270 6
            static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
271 6
            $dstExists = true;
272
        }
273
274 15
        $handle = opendir($src);
275 15
        if ($handle === false) {
276
            throw new InvalidParamException("Unable to open directory: $src");
277
        }
278 15
        if (!isset($options['basePath'])) {
279
            // this should be done only once
280 15
            $options['basePath'] = realpath($src);
281 15
            $options = static::normalizeOptions($options);
282
        }
283 15
        while (($file = readdir($handle)) !== false) {
284 15
            if ($file === '.' || $file === '..') {
285 15
                continue;
286
            }
287 13
            $from = $src . DIRECTORY_SEPARATOR . $file;
288 13
            $to = $dst . DIRECTORY_SEPARATOR . $file;
289 13
            if (static::filterPath($from, $options)) {
290 13
                if (isset($options['beforeCopy']) && !call_user_func($options['beforeCopy'], $from, $to)) {
291 2
                    continue;
292
                }
293 11
                if (is_file($from)) {
294 11
                    if (!$dstExists) {
295
                        // delay creation of destination directory until the first file is copied to avoid creating empty directories
296 5
                        static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
297 5
                        $dstExists = true;
298
                    }
299 11
                    copy($from, $to);
300 11
                    if (isset($options['fileMode'])) {
301 11
                        @chmod($to, $options['fileMode']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
302
                    }
303
                } else {
304
                    // recursive copy, defaults to true
305 8
                    if (!isset($options['recursive']) || $options['recursive']) {
306 7
                        static::copyDirectory($from, $to, $options);
307
                    }
308
                }
309 11
                if (isset($options['afterCopy'])) {
310
                    call_user_func($options['afterCopy'], $from, $to);
311
                }
312
            }
313
        }
314 15
        closedir($handle);
315 15
    }
316
317
    /**
318
     * Removes a directory (and all its content) recursively.
319
     *
320
     * @param string $dir the directory to be deleted recursively.
321
     * @param array $options options for directory remove. Valid options are:
322
     *
323
     * - traverseSymlinks: boolean, whether symlinks to the directories should be traversed too.
324
     *   Defaults to `false`, meaning the content of the symlinked directory would not be deleted.
325
     *   Only symlink would be removed in that default case.
326
     *
327
     * @throws ErrorException in case of failure
328
     */
329 112
    public static function removeDirectory($dir, $options = [])
330
    {
331 112
        if (!is_dir($dir)) {
332 27
            return;
333
        }
334 111
        if (isset($options['traverseSymlinks']) && $options['traverseSymlinks'] || !is_link($dir)) {
335 111
            if (!($handle = opendir($dir))) {
336
                return;
337
            }
338 111
            while (($file = readdir($handle)) !== false) {
339 111
                if ($file === '.' || $file === '..') {
340 111
                    continue;
341
                }
342 94
                $path = $dir . DIRECTORY_SEPARATOR . $file;
343 94
                if (is_dir($path)) {
344 53
                    static::removeDirectory($path, $options);
345
                } else {
346
                    try {
347 75
                        unlink($path);
348
                    } catch (ErrorException $e) {
349
                        if (DIRECTORY_SEPARATOR === '\\') {
350
                            // last resort measure for Windows
351
                            $lines = [];
352
                            exec("DEL /F/Q \"$path\"", $lines, $deleteError);
353
                        } else {
354
                            throw $e;
355
                        }
356
                    }
357
                }
358
            }
359 111
            closedir($handle);
360
        }
361 111
        if (is_link($dir)) {
362 2
            unlink($dir);
363
        } else {
364 111
            rmdir($dir);
365
        }
366 111
    }
367
368
    /**
369
     * Returns the files found under the specified directory and subdirectories.
370
     * @param string $dir the directory under which the files will be looked for.
371
     * @param array $options options for file searching. Valid options are:
372
     *
373
     * - `filter`: callback, a PHP callback that is called for each directory or file.
374
     *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
375
     *   The callback can return one of the following values:
376
     *
377
     *   * `true`: the directory or file will be returned (the `only` and `except` options will be ignored)
378
     *   * `false`: the directory or file will NOT be returned (the `only` and `except` options will be ignored)
379
     *   * `null`: the `only` and `except` options will determine whether the directory or file should be returned
380
     *
381
     * - `except`: array, list of patterns excluding from the results matching file or directory paths.
382
     *   Patterns ending with slash ('/') apply to directory paths only, and patterns not ending with '/'
383
     *   apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
384
     *   and `.svn/` matches directory paths ending with `.svn`.
385
     *   If the pattern does not contain a slash (`/`), it is treated as a shell glob pattern
386
     *   and checked for a match against the pathname relative to `$dir`.
387
     *   Otherwise, the pattern is treated as a shell glob suitable for consumption by `fnmatch(3)`
388
     *   with the `FNM_PATHNAME` flag: wildcards in the pattern will not match a `/` in the pathname.
389
     *   For example, `views/*.php` matches `views/index.php` but not `views/controller/index.php`.
390
     *   A leading slash matches the beginning of the pathname. For example, `/*.php` matches `index.php` but not `views/start/index.php`.
391
     *   An optional prefix `!` which negates the pattern; any matching file excluded by a previous pattern will become included again.
392
     *   If a negated pattern matches, this will override lower precedence patterns sources. Put a backslash (`\`) in front of the first `!`
393
     *   for patterns that begin with a literal `!`, for example, `\!important!.txt`.
394
     *   Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
395
     * - `only`: array, list of patterns that the file paths should match if they are to be returned. Directory paths
396
     *   are not checked against them. Same pattern matching rules as in the `except` option are used.
397
     *   If a file path matches a pattern in both `only` and `except`, it will NOT be returned.
398
     * - `caseSensitive`: boolean, whether patterns specified at `only` or `except` should be case sensitive. Defaults to `true`.
399
     * - `recursive`: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`.
400
     * @return array files found under the directory, in no particular order. Ordering depends on the files system used.
401
     * @throws InvalidParamException if the dir is invalid.
402
     */
403 65
    public static function findFiles($dir, $options = [])
404
    {
405 65
        if (!is_dir($dir)) {
406
            throw new InvalidParamException("The dir argument must be a directory: $dir");
407
        }
408 65
        $dir = rtrim($dir, DIRECTORY_SEPARATOR);
409 65
        if (!isset($options['basePath'])) {
410
            // this should be done only once
411 65
            $options['basePath'] = realpath($dir);
412 65
            $options = static::normalizeOptions($options);
413
        }
414 65
        $list = [];
415 65
        $handle = opendir($dir);
416 65
        if ($handle === false) {
417
            throw new InvalidParamException("Unable to open directory: $dir");
418
        }
419 65
        while (($file = readdir($handle)) !== false) {
420 65
            if ($file === '.' || $file === '..') {
421 65
                continue;
422
            }
423 65
            $path = $dir . DIRECTORY_SEPARATOR . $file;
424 65
            if (static::filterPath($path, $options)) {
425 65
                if (is_file($path)) {
426 63
                    $list[] = $path;
427 20
                } elseif (is_dir($path) && (!isset($options['recursive']) || $options['recursive'])) {
428 19
                    $list = array_merge($list, static::findFiles($path, $options));
429
                }
430
            }
431
        }
432 65
        closedir($handle);
433
434 65
        return $list;
435
    }
436
437
    /**
438
     * Checks if the given file path satisfies the filtering options.
439
     * @param string $path the path of the file or directory to be checked
440
     * @param array $options the filtering options. See [[findFiles()]] for explanations of
441
     * the supported options.
442
     * @return bool whether the file or directory satisfies the filtering options.
443
     */
444 74
    public static function filterPath($path, $options)
445
    {
446 74
        if (isset($options['filter'])) {
447 1
            $result = call_user_func($options['filter'], $path);
448 1
            if (is_bool($result)) {
449 1
                return $result;
450
            }
451
        }
452
453 73
        if (empty($options['except']) && empty($options['only'])) {
454 23
            return true;
455
        }
456
457 54
        $path = str_replace('\\', '/', $path);
458
459 54
        if (!empty($options['except'])) {
460 35
            if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null) {
461 2
                return $except['flags'] & self::PATTERN_NEGATIVE;
462
            }
463
        }
464
465 54
        if (!empty($options['only']) && !is_dir($path)) {
466 53
            if (($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only'])) !== null) {
467
                // don't check PATTERN_NEGATIVE since those entries are not prefixed with !
468 51
                return true;
469
            }
470
471 19
            return false;
472
        }
473
474 18
        return true;
475
    }
476
477
    /**
478
     * Creates a new directory.
479
     *
480
     * This method is similar to the PHP `mkdir()` function except that
481
     * it uses `chmod()` to set the permission of the created directory
482
     * in order to avoid the impact of the `umask` setting.
483
     *
484
     * @param string $path path of the directory to be created.
485
     * @param int $mode the permission to be set for the created directory.
486
     * @param bool $recursive whether to create parent directories if they do not exist.
487
     * @return bool whether the directory is created successfully
488
     * @throws \yii\base\Exception if the directory could not be created (i.e. php error due to parallel changes)
489
     */
490 164
    public static function createDirectory($path, $mode = 0775, $recursive = true)
491
    {
492 164
        if (is_dir($path)) {
493 62
            return true;
494
        }
495 140
        $parentDir = dirname($path);
496
        // recurse if parent dir does not exist and we are not at the root of the file system.
497 140
        if ($recursive && !is_dir($parentDir) && $parentDir !== $path) {
498 5
            static::createDirectory($parentDir, $mode, true);
499
        }
500
        try {
501 140
            if (!mkdir($path, $mode)) {
502 140
                return false;
503
            }
504
        } catch (\Exception $e) {
505
            if (!is_dir($path)) {// https://github.com/yiisoft/yii2/issues/9288
506
                throw new \yii\base\Exception("Failed to create directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
507
            }
508
        }
509
        try {
510 140
            return chmod($path, $mode);
511
        } catch (\Exception $e) {
512
            throw new \yii\base\Exception("Failed to change permissions for directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
513
        }
514
    }
515
516
    /**
517
     * Performs a simple comparison of file or directory names.
518
     *
519
     * Based on match_basename() from dir.c of git 1.8.5.3 sources.
520
     *
521
     * @param string $baseName file or directory name to compare with the pattern
522
     * @param string $pattern the pattern that $baseName will be compared against
523
     * @param int|bool $firstWildcard location of first wildcard character in the $pattern
524
     * @param int $flags pattern flags
525
     * @return bool whether the name matches against pattern
526
     */
527 53
    private static function matchBasename($baseName, $pattern, $firstWildcard, $flags)
528
    {
529 53
        if ($firstWildcard === false) {
530 43
            if ($pattern === $baseName) {
531 43
                return true;
532
            }
533 43
        } elseif ($flags & self::PATTERN_ENDSWITH) {
534
            /* "*literal" matching against "fooliteral" */
535 42
            $n = StringHelper::byteLength($pattern);
536 42
            if (StringHelper::byteSubstr($pattern, 1, $n) === StringHelper::byteSubstr($baseName, -$n, $n)) {
537
                return true;
538
            }
539
        }
540
541 53
        $fnmatchFlags = 0;
542 53
        if ($flags & self::PATTERN_CASE_INSENSITIVE) {
543 1
            $fnmatchFlags |= FNM_CASEFOLD;
544
        }
545
546 53
        return fnmatch($pattern, $baseName, $fnmatchFlags);
547
    }
548
549
    /**
550
     * Compares a path part against a pattern with optional wildcards.
551
     *
552
     * Based on match_pathname() from dir.c of git 1.8.5.3 sources.
553
     *
554
     * @param string $path full path to compare
555
     * @param string $basePath base of path that will not be compared
556
     * @param string $pattern the pattern that path part will be compared against
557
     * @param int|bool $firstWildcard location of first wildcard character in the $pattern
558
     * @param int $flags pattern flags
559
     * @return bool whether the path part matches against pattern
560
     */
561 37
    private static function matchPathname($path, $basePath, $pattern, $firstWildcard, $flags)
562
    {
563
        // match with FNM_PATHNAME; the pattern has base implicitly in front of it.
564 37
        if (isset($pattern[0]) && $pattern[0] === '/') {
565 34
            $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
566 34
            if ($firstWildcard !== false && $firstWildcard !== 0) {
567
                $firstWildcard--;
568
            }
569
        }
570
571 37
        $namelen = StringHelper::byteLength($path) - (empty($basePath) ? 0 : StringHelper::byteLength($basePath) + 1);
572 37
        $name = StringHelper::byteSubstr($path, -$namelen, $namelen);
573
574 37
        if ($firstWildcard !== 0) {
575 37
            if ($firstWildcard === false) {
576 36
                $firstWildcard = StringHelper::byteLength($pattern);
577
            }
578
            // if the non-wildcard part is longer than the remaining pathname, surely it cannot match.
579 37
            if ($firstWildcard > $namelen) {
580 2
                return false;
581
            }
582
583 37
            if (strncmp($pattern, $name, $firstWildcard)) {
584 37
                return false;
585
            }
586 4
            $pattern = StringHelper::byteSubstr($pattern, $firstWildcard, StringHelper::byteLength($pattern));
587 4
            $name = StringHelper::byteSubstr($name, $firstWildcard, $namelen);
588
589
            // If the whole pattern did not have a wildcard, then our prefix match is all we need; we do not need to call fnmatch at all.
590 4
            if (empty($pattern) && empty($name)) {
591 3
                return true;
592
            }
593
        }
594
595 2
        $fnmatchFlags = FNM_PATHNAME;
596 2
        if ($flags & self::PATTERN_CASE_INSENSITIVE) {
597
            $fnmatchFlags |= FNM_CASEFOLD;
598
        }
599
600 2
        return fnmatch($pattern, $name, $fnmatchFlags);
601
    }
602
603
    /**
604
     * Scan the given exclude list in reverse to see whether pathname
605
     * should be ignored.  The first match (i.e. the last on the list), if
606
     * any, determines the fate.  Returns the element which
607
     * matched, or null for undecided.
608
     *
609
     * Based on last_exclude_matching_from_list() from dir.c of git 1.8.5.3 sources.
610
     *
611
     * @param string $basePath
612
     * @param string $path
613
     * @param array $excludes list of patterns to match $path against
614
     * @return array|null null or one of $excludes item as an array with keys: 'pattern', 'flags'
615
     * @throws InvalidParamException if any of the exclude patterns is not a string or an array with keys: pattern, flags, firstWildcard.
616
     */
617 54
    private static function lastExcludeMatchingFromList($basePath, $path, $excludes)
618
    {
619 54
        foreach (array_reverse($excludes) as $exclude) {
620 54
            if (is_string($exclude)) {
621
                $exclude = self::parseExcludePattern($exclude, false);
622
            }
623 54
            if (!isset($exclude['pattern']) || !isset($exclude['flags']) || !isset($exclude['firstWildcard'])) {
624
                throw new InvalidParamException('If exclude/include pattern is an array it must contain the pattern, flags and firstWildcard keys.');
625
            }
626 54
            if ($exclude['flags'] & self::PATTERN_MUSTBEDIR && !is_dir($path)) {
627
                continue;
628
            }
629
630 54
            if ($exclude['flags'] & self::PATTERN_NODIR) {
631 53
                if (self::matchBasename(basename($path), $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
632 51
                    return $exclude;
633
                }
634 52
                continue;
635
            }
636
637 37
            if (self::matchPathname($path, $basePath, $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
638 37
                return $exclude;
639
            }
640
        }
641
642 53
        return null;
643
    }
644
645
    /**
646
     * Processes the pattern, stripping special characters like / and ! from the beginning and settings flags instead.
647
     * @param string $pattern
648
     * @param bool $caseSensitive
649
     * @throws \yii\base\InvalidParamException
650
     * @return array with keys: (string) pattern, (int) flags, (int|bool) firstWildcard
651
     */
652 54
    private static function parseExcludePattern($pattern, $caseSensitive)
653
    {
654 54
        if (!is_string($pattern)) {
655
            throw new InvalidParamException('Exclude/include pattern must be a string.');
656
        }
657
658
        $result = [
659 54
            'pattern' => $pattern,
660 54
            'flags' => 0,
661
            'firstWildcard' => false,
662
        ];
663
664 54
        if (!$caseSensitive) {
665 1
            $result['flags'] |= self::PATTERN_CASE_INSENSITIVE;
666
        }
667
668 54
        if (!isset($pattern[0])) {
669
            return $result;
670
        }
671
672 54
        if ($pattern[0] === '!') {
673
            $result['flags'] |= self::PATTERN_NEGATIVE;
674
            $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
675
        }
676 54
        if (StringHelper::byteLength($pattern) && StringHelper::byteSubstr($pattern, -1, 1) === '/') {
677
            $pattern = StringHelper::byteSubstr($pattern, 0, -1);
678
            $result['flags'] |= self::PATTERN_MUSTBEDIR;
679
        }
680 54
        if (strpos($pattern, '/') === false) {
681 53
            $result['flags'] |= self::PATTERN_NODIR;
682
        }
683 54
        $result['firstWildcard'] = self::firstWildcardInPattern($pattern);
684 54
        if ($pattern[0] === '*' && self::firstWildcardInPattern(StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern))) === false) {
685 42
            $result['flags'] |= self::PATTERN_ENDSWITH;
686
        }
687 54
        $result['pattern'] = $pattern;
688
689 54
        return $result;
690
    }
691
692
    /**
693
     * Searches for the first wildcard character in the pattern.
694
     * @param string $pattern the pattern to search in
695
     * @return int|bool position of first wildcard character or false if not found
696
     */
697 54
    private static function firstWildcardInPattern($pattern)
698
    {
699 54
        $wildcards = ['*', '?', '[', '\\'];
700 54
        $wildcardSearch = function ($r, $c) use ($pattern) {
701 54
            $p = strpos($pattern, $c);
702
703 54
            return $r === false ? $p : ($p === false ? $r : min($r, $p));
704 54
        };
705
706 54
        return array_reduce($wildcards, $wildcardSearch, false);
707
    }
708
709
    /**
710
     * @param array $options raw options
711
     * @return array normalized options
712
     * @since 2.0.12
713
     */
714 76
    protected static function normalizeOptions(array $options)
715
    {
716 76
        if (!array_key_exists('caseSensitive', $options)) {
717 75
            $options['caseSensitive'] = true;
718
        }
719 76
        if (isset($options['except'])) {
720 35
            foreach ($options['except'] as $key => $value) {
721 35
                if (is_string($value)) {
722 35
                    $options['except'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
723
                }
724
            }
725
        }
726 76
        if (isset($options['only'])) {
727 53
            foreach ($options['only'] as $key => $value) {
728 53
                if (is_string($value)) {
729 53
                    $options['only'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
730
                }
731
            }
732
        }
733
734 76
        return $options;
735
    }
736
}
737