Passed
Push — master ( 7b3695...7ed855 )
by Alexander
14:00
created

BaseFileHelper::parseExcludePattern()   B

Complexity

Conditions 10
Paths 35

Size

Total Lines 38
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 10.6008

Importance

Changes 0
Metric Value
cc 10
eloc 23
nc 35
nop 2
dl 0
loc 38
ccs 18
cts 22
cp 0.8182
crap 10.6008
rs 7.6666
c 0
b 0
f 0

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

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

159
                return static::getMimeTypeByExtension($file, /** @scrutinizer ignore-type */ $magicFile);
Loading history...
160
            }
161
162
            throw new InvalidConfigException('The fileinfo PHP extension is not installed.');
163
        }
164
165 32
        $info = finfo_open(FILEINFO_MIME_TYPE, $magicFile);
0 ignored issues
show
Bug introduced by
It seems like $magicFile can also be of type false and null; however, parameter $magic_database of finfo_open() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

165
        $info = finfo_open(FILEINFO_MIME_TYPE, /** @scrutinizer ignore-type */ $magicFile);
Loading history...
166
167 32
        if ($info) {
0 ignored issues
show
introduced by
$info is of type resource, thus it always evaluated to false.
Loading history...
168 32
            $result = finfo_file($info, $file);
169 32
            finfo_close($info);
170
171 32
            if ($result !== false) {
172 32
                return $result;
173
            }
174
        }
175
176
        return $checkExtension ? static::getMimeTypeByExtension($file, $magicFile) : null;
177
    }
178
179
    /**
180
     * Determines the MIME type based on the extension name of the specified file.
181
     * This method will use a local map between extension names and MIME types.
182
     * @param string $file the file name.
183
     * @param string|null $magicFile the path (or alias) of the file that contains all available MIME type information.
184
     * If this is not set, the file specified by [[mimeMagicFile]] will be used.
185
     * @return string|null the MIME type. Null is returned if the MIME type cannot be determined.
186
     */
187 11
    public static function getMimeTypeByExtension($file, $magicFile = null)
188
    {
189 11
        $mimeTypes = static::loadMimeTypes($magicFile);
190
191 11
        if (($ext = pathinfo($file, PATHINFO_EXTENSION)) !== '') {
192 11
            $ext = strtolower($ext);
0 ignored issues
show
Bug introduced by
It seems like $ext can also be of type array; however, parameter $string of strtolower() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

192
            $ext = strtolower(/** @scrutinizer ignore-type */ $ext);
Loading history...
193 11
            if (isset($mimeTypes[$ext])) {
194 11
                return $mimeTypes[$ext];
195
            }
196
        }
197
198 1
        return null;
199
    }
200
201
    /**
202
     * Determines the extensions by given MIME type.
203
     * This method will use a local map between extension names and MIME types.
204
     * @param string $mimeType file MIME type.
205
     * @param string|null $magicFile the path (or alias) of the file that contains all available MIME type information.
206
     * If this is not set, the file specified by [[mimeMagicFile]] will be used.
207
     * @return array the extensions corresponding to the specified MIME type
208
     */
209 13
    public static function getExtensionsByMimeType($mimeType, $magicFile = null)
210
    {
211 13
        $aliases = static::loadMimeAliases(static::$mimeAliasesFile);
212 13
        if (isset($aliases[$mimeType])) {
213 2
            $mimeType = $aliases[$mimeType];
214
        }
215
216 13
        $mimeTypes = static::loadMimeTypes($magicFile);
217 13
        return array_keys($mimeTypes, mb_strtolower($mimeType, 'UTF-8'), true);
218
    }
219
220
    private static $_mimeTypes = [];
221
222
    /**
223
     * Loads MIME types from the specified file.
224
     * @param string|null $magicFile the path (or alias) of the file that contains all available MIME type information.
225
     * If this is not set, the file specified by [[mimeMagicFile]] will be used.
226
     * @return array the mapping from file extensions to MIME types
227
     */
228 24
    protected static function loadMimeTypes($magicFile)
229
    {
230 24
        if ($magicFile === null) {
231 24
            $magicFile = static::$mimeMagicFile;
232
        }
233 24
        $magicFile = Yii::getAlias($magicFile);
234 24
        if (!isset(self::$_mimeTypes[$magicFile])) {
235 1
            self::$_mimeTypes[$magicFile] = require $magicFile;
236
        }
237
238 24
        return self::$_mimeTypes[$magicFile];
239
    }
240
241
    private static $_mimeAliases = [];
242
243
    /**
244
     * Loads MIME aliases from the specified file.
245
     * @param string|null $aliasesFile the path (or alias) of the file that contains MIME type aliases.
246
     * If this is not set, the file specified by [[mimeAliasesFile]] will be used.
247
     * @return array the mapping from file extensions to MIME types
248
     * @since 2.0.14
249
     */
250 13
    protected static function loadMimeAliases($aliasesFile)
251
    {
252 13
        if ($aliasesFile === null) {
253
            $aliasesFile = static::$mimeAliasesFile;
254
        }
255 13
        $aliasesFile = Yii::getAlias($aliasesFile);
256 13
        if (!isset(self::$_mimeAliases[$aliasesFile])) {
257 1
            self::$_mimeAliases[$aliasesFile] = require $aliasesFile;
258
        }
259
260 13
        return self::$_mimeAliases[$aliasesFile];
261
    }
262
263
    /**
264
     * Copies a whole directory as another one.
265
     * The files and sub-directories will also be copied over.
266
     * @param string $src the source directory
267
     * @param string $dst the destination directory
268
     * @param array $options options for directory copy. Valid options are:
269
     *
270
     * - dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
271
     * - fileMode:  integer, the permission to be set for newly copied files. Defaults to the current environment setting.
272
     * - filter: callback, a PHP callback that is called for each directory or file.
273
     *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
274
     *   The callback can return one of the following values:
275
     *
276
     *   * true: the directory or file will be copied (the "only" and "except" options will be ignored)
277
     *   * false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
278
     *   * null: the "only" and "except" options will determine whether the directory or file should be copied
279
     *
280
     * - only: array, list of patterns that the file paths should match if they want to be copied.
281
     *   A path matches a pattern if it contains the pattern string at its end.
282
     *   For example, '.php' matches all file paths ending with '.php'.
283
     *   Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
284
     *   If a file path matches a pattern in both "only" and "except", it will NOT be copied.
285
     * - except: array, list of patterns that the files or directories should match if they want to be excluded from being copied.
286
     *   A path matches a pattern if it contains the pattern string at its end.
287
     *   Patterns ending with '/' apply to directory paths only, and patterns not ending with '/'
288
     *   apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
289
     *   and '.svn/' matches directory paths ending with '.svn'. Note, the '/' characters in a pattern matches
290
     *   both '/' and '\' in the paths.
291
     * - caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.
292
     * - recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true.
293
     * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file.
294
     *   If the callback returns false, the copy operation for the sub-directory or file will be cancelled.
295
     *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
296
     *   file to be copied from, while `$to` is the copy target.
297
     * - afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied.
298
     *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or
299
     *   file copied from, while `$to` is the copy target.
300
     * - copyEmptyDirectories: boolean, whether to copy empty directories. Set this to false to avoid creating directories
301
     *   that do not contain files. This affects directories that do not contain files initially as well as directories that
302
     *   do not contain files at the target destination because files have been filtered via `only` or `except`.
303
     *   Defaults to true. This option is available since version 2.0.12. Before 2.0.12 empty directories are always copied.
304
     * @throws InvalidArgumentException if unable to open directory
305
     */
306 17
    public static function copyDirectory($src, $dst, $options = [])
307
    {
308 17
        $src = static::normalizePath($src);
309 17
        $dst = static::normalizePath($dst);
310
311 17
        if ($src === $dst || strpos($dst, $src . DIRECTORY_SEPARATOR) === 0) {
312 2
            throw new InvalidArgumentException('Trying to copy a directory to itself or a subdirectory.');
313
        }
314 15
        $dstExists = is_dir($dst);
315 15
        if (!$dstExists && (!isset($options['copyEmptyDirectories']) || $options['copyEmptyDirectories'])) {
316 6
            static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
317 6
            $dstExists = true;
318
        }
319
320 15
        $handle = opendir($src);
321 15
        if ($handle === false) {
322
            throw new InvalidArgumentException("Unable to open directory: $src");
323
        }
324 15
        if (!isset($options['basePath'])) {
325
            // this should be done only once
326 15
            $options['basePath'] = realpath($src);
327 15
            $options = static::normalizeOptions($options);
328
        }
329 15
        while (($file = readdir($handle)) !== false) {
330 15
            if ($file === '.' || $file === '..') {
331 15
                continue;
332
            }
333 13
            $from = $src . DIRECTORY_SEPARATOR . $file;
334 13
            $to = $dst . DIRECTORY_SEPARATOR . $file;
335 13
            if (static::filterPath($from, $options)) {
336 13
                if (isset($options['beforeCopy']) && !call_user_func($options['beforeCopy'], $from, $to)) {
337 2
                    continue;
338
                }
339 11
                if (is_file($from)) {
340 11
                    if (!$dstExists) {
341
                        // delay creation of destination directory until the first file is copied to avoid creating empty directories
342 5
                        static::createDirectory($dst, isset($options['dirMode']) ? $options['dirMode'] : 0775, true);
343 5
                        $dstExists = true;
344
                    }
345 11
                    copy($from, $to);
346 11
                    if (isset($options['fileMode'])) {
347 11
                        @chmod($to, $options['fileMode']);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for chmod(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

347
                        /** @scrutinizer ignore-unhandled */ @chmod($to, $options['fileMode']);

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...
348
                    }
349
                } else {
350
                    // recursive copy, defaults to true
351 8
                    if (!isset($options['recursive']) || $options['recursive']) {
352 7
                        static::copyDirectory($from, $to, $options);
353
                    }
354
                }
355 11
                if (isset($options['afterCopy'])) {
356
                    call_user_func($options['afterCopy'], $from, $to);
357
                }
358
            }
359
        }
360 15
        closedir($handle);
361 15
    }
362
363
    /**
364
     * Removes a directory (and all its content) recursively.
365
     *
366
     * @param string $dir the directory to be deleted recursively.
367
     * @param array $options options for directory remove. Valid options are:
368
     *
369
     * - traverseSymlinks: boolean, whether symlinks to the directories should be traversed too.
370
     *   Defaults to `false`, meaning the content of the symlinked directory would not be deleted.
371
     *   Only symlink would be removed in that default case.
372
     *
373
     * @throws ErrorException in case of failure
374
     */
375 223
    public static function removeDirectory($dir, $options = [])
376
    {
377 223
        if (!is_dir($dir)) {
378 108
            return;
379
        }
380 221
        if (!empty($options['traverseSymlinks']) || !is_link($dir)) {
381 221
            if (!($handle = opendir($dir))) {
382
                return;
383
            }
384 221
            while (($file = readdir($handle)) !== false) {
385 221
                if ($file === '.' || $file === '..') {
386 221
                    continue;
387
                }
388 198
                $path = $dir . DIRECTORY_SEPARATOR . $file;
389 198
                if (is_dir($path)) {
390 76
                    static::removeDirectory($path, $options);
391
                } else {
392 176
                    static::unlink($path);
393
                }
394
            }
395 221
            closedir($handle);
396
        }
397 221
        if (is_link($dir)) {
398 2
            static::unlink($dir);
399
        } else {
400 221
            rmdir($dir);
401
        }
402 221
    }
403
404
    /**
405
     * Removes a file or symlink in a cross-platform way
406
     *
407
     * @param string $path
408
     * @return bool
409
     *
410
     * @since 2.0.14
411
     */
412 177
    public static function unlink($path)
413
    {
414 177
        $isWindows = DIRECTORY_SEPARATOR === '\\';
415
416 177
        if (!$isWindows) {
417 177
            return unlink($path);
418
        }
419
420
        if (is_link($path) && is_dir($path)) {
421
            return rmdir($path);
422
        }
423
424
        try {
425
            return unlink($path);
426
        } catch (ErrorException $e) {
427
            // last resort measure for Windows
428
            if (is_dir($path) && count(static::findFiles($path)) !== 0) {
429
                return false;
430
            }
431
            if (function_exists('exec') && file_exists($path)) {
432
                exec('DEL /F/Q ' . escapeshellarg($path));
433
434
                return !file_exists($path);
435
            }
436
437
            return false;
438
        }
439
    }
440
441
    /**
442
     * Returns the files found under the specified directory and subdirectories.
443
     * @param string $dir the directory under which the files will be looked for.
444
     * @param array $options options for file searching. Valid options are:
445
     *
446
     * - `filter`: callback, a PHP callback that is called for each directory or file.
447
     *   The signature of the callback should be: `function ($path)`, where `$path` refers the full path to be filtered.
448
     *   The callback can return one of the following values:
449
     *
450
     *   * `true`: the directory or file will be returned (the `only` and `except` options will be ignored)
451
     *   * `false`: the directory or file will NOT be returned (the `only` and `except` options will be ignored)
452
     *   * `null`: the `only` and `except` options will determine whether the directory or file should be returned
453
     *
454
     * - `except`: array, list of patterns excluding from the results matching file or directory paths.
455
     *   Patterns ending with slash ('/') apply to directory paths only, and patterns not ending with '/'
456
     *   apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b';
457
     *   and `.svn/` matches directory paths ending with `.svn`.
458
     *   If the pattern does not contain a slash (`/`), it is treated as a shell glob pattern
459
     *   and checked for a match against the pathname relative to `$dir`.
460
     *   Otherwise, the pattern is treated as a shell glob suitable for consumption by `fnmatch(3)`
461
     *   with the `FNM_PATHNAME` flag: wildcards in the pattern will not match a `/` in the pathname.
462
     *   For example, `views/*.php` matches `views/index.php` but not `views/controller/index.php`.
463
     *   A leading slash matches the beginning of the pathname. For example, `/*.php` matches `index.php` but not `views/start/index.php`.
464
     *   An optional prefix `!` which negates the pattern; any matching file excluded by a previous pattern will become included again.
465
     *   If a negated pattern matches, this will override lower precedence patterns sources. Put a backslash (`\`) in front of the first `!`
466
     *   for patterns that begin with a literal `!`, for example, `\!important!.txt`.
467
     *   Note, the '/' characters in a pattern matches both '/' and '\' in the paths.
468
     *   You can find more details about the gitignore pattern format [here](https://git-scm.com/docs/gitignore/en#_pattern_format).
469
     * - `only`: array, list of patterns that the file paths should match if they are to be returned. Directory paths
470
     *   are not checked against them. Same pattern matching rules as in the `except` option are used.
471
     *   If a file path matches a pattern in both `only` and `except`, it will NOT be returned.
472
     * - `caseSensitive`: boolean, whether patterns specified at `only` or `except` should be case sensitive. Defaults to `true`.
473
     * - `recursive`: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`.
474
     * @return array files found under the directory, in no particular order. Ordering depends on the files system used.
475
     * @throws InvalidArgumentException if the dir is invalid.
476
     */
477 167
    public static function findFiles($dir, $options = [])
478
    {
479 167
        $dir = self::clearDir($dir);
480 167
        $options = self::setBasePath($dir, $options);
481 167
        $list = [];
482 167
        $handle = self::openDir($dir);
483 167
        while (($file = readdir($handle)) !== false) {
484 167
            if ($file === '.' || $file === '..') {
485 167
                continue;
486
            }
487 164
            $path = $dir . DIRECTORY_SEPARATOR . $file;
488 164
            if (static::filterPath($path, $options)) {
489 164
                if (is_file($path)) {
490 162
                    $list[] = $path;
491 25
                } elseif (is_dir($path) && (!isset($options['recursive']) || $options['recursive'])) {
492 24
                    $list = array_merge($list, static::findFiles($path, $options));
493
                }
494
            }
495
        }
496 167
        closedir($handle);
497
498 167
        return $list;
499
    }
500
501
    /**
502
     * Returns the directories found under the specified directory and subdirectories.
503
     * @param string $dir the directory under which the files will be looked for.
504
     * @param array $options options for directory searching. Valid options are:
505
     *
506
     * - `filter`: callback, a PHP callback that is called for each directory or file.
507
     *   The signature of the callback should be: `function (string $path): bool`, where `$path` refers
508
     *   the full path to be filtered. The callback can return one of the following values:
509
     *
510
     *   * `true`: the directory will be returned
511
     *   * `false`: the directory will NOT be returned
512
     *
513
     * - `recursive`: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`.
514
     *   See [[findFiles()]] for more options.
515
     * @return array directories found under the directory, in no particular order. Ordering depends on the files system used.
516
     * @throws InvalidArgumentException if the dir is invalid.
517
     * @since 2.0.14
518
     */
519 1
    public static function findDirectories($dir, $options = [])
520
    {
521 1
        $dir = self::clearDir($dir);
522 1
        $options = self::setBasePath($dir, $options);
523 1
        $list = [];
524 1
        $handle = self::openDir($dir);
525 1
        while (($file = readdir($handle)) !== false) {
526 1
            if ($file === '.' || $file === '..') {
527 1
                continue;
528
            }
529 1
            $path = $dir . DIRECTORY_SEPARATOR . $file;
530 1
            if (is_dir($path) && static::filterPath($path, $options)) {
531 1
                $list[] = $path;
532 1
                if (!isset($options['recursive']) || $options['recursive']) {
533 1
                    $list = array_merge($list, static::findDirectories($path, $options));
534
                }
535
            }
536
        }
537 1
        closedir($handle);
538
539 1
        return $list;
540
    }
541
542
    /**
543
     * @param string $dir
544
     * @param array $options
545
     * @return array
546
     */
547 168
    private static function setBasePath($dir, $options)
548
    {
549 168
        if (!isset($options['basePath'])) {
550
            // this should be done only once
551 168
            $options['basePath'] = realpath($dir);
552 168
            $options = static::normalizeOptions($options);
553
        }
554
555 168
        return $options;
556
    }
557
558
    /**
559
     * @param string $dir
560
     * @return resource
561
     * @throws InvalidArgumentException if unable to open directory
562
     */
563 168
    private static function openDir($dir)
564
    {
565 168
        $handle = opendir($dir);
566 168
        if ($handle === false) {
567
            throw new InvalidArgumentException("Unable to open directory: $dir");
568
        }
569 168
        return $handle;
570
    }
571
572
    /**
573
     * @param string $dir
574
     * @return string
575
     * @throws InvalidArgumentException if directory not exists
576
     */
577 168
    private static function clearDir($dir)
578
    {
579 168
        if (!is_dir($dir)) {
580
            throw new InvalidArgumentException("The dir argument must be a directory: $dir");
581
        }
582 168
        return rtrim($dir, '\/');
583
    }
584
585
    /**
586
     * Checks if the given file path satisfies the filtering options.
587
     * @param string $path the path of the file or directory to be checked
588
     * @param array $options the filtering options. See [[findFiles()]] for explanations of
589
     * the supported options.
590
     * @return bool whether the file or directory satisfies the filtering options.
591
     */
592 174
    public static function filterPath($path, $options)
593
    {
594 174
        if (isset($options['filter'])) {
595 2
            $result = call_user_func($options['filter'], $path);
596 2
            if (is_bool($result)) {
597 2
                return $result;
598
            }
599
        }
600
601 173
        if (empty($options['except']) && empty($options['only'])) {
602 106
            return true;
603
        }
604
605 76
        $path = str_replace('\\', '/', $path);
606
607
        if (
608 76
            !empty($options['except'])
609 76
            && ($except = self::lastExcludeMatchingFromList($options['basePath'], $path, $options['except'])) !== null
610
        ) {
611 3
            return $except['flags'] & self::PATTERN_NEGATIVE;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $except['flags'] & self::PATTERN_NEGATIVE returns the type integer which is incompatible with the documented return type boolean.
Loading history...
612
        }
613
614 76
        if (!empty($options['only']) && !is_dir($path)) {
615 74
            return self::lastExcludeMatchingFromList($options['basePath'], $path, $options['only']) !== null;
616
        }
617
618 20
        return true;
619
    }
620
621
    /**
622
     * Creates a new directory.
623
     *
624
     * This method is similar to the PHP `mkdir()` function except that
625
     * it uses `chmod()` to set the permission of the created directory
626
     * in order to avoid the impact of the `umask` setting.
627
     *
628
     * @param string $path path of the directory to be created.
629
     * @param int $mode the permission to be set for the created directory.
630
     * @param bool $recursive whether to create parent directories if they do not exist.
631
     * @return bool whether the directory is created successfully
632
     * @throws \yii\base\Exception if the directory could not be created (i.e. php error due to parallel changes)
633
     */
634 276
    public static function createDirectory($path, $mode = 0775, $recursive = true)
635
    {
636 276
        if (is_dir($path)) {
637 166
            return true;
638
        }
639 252
        $parentDir = dirname($path);
640
        // recurse if parent dir does not exist and we are not at the root of the file system.
641 252
        if ($recursive && !is_dir($parentDir) && $parentDir !== $path) {
642 5
            static::createDirectory($parentDir, $mode, true);
643
        }
644
        try {
645 252
            if (!mkdir($path, $mode)) {
646 252
                return false;
647
            }
648
        } catch (\Exception $e) {
649
            if (!is_dir($path)) {// https://github.com/yiisoft/yii2/issues/9288
650
                throw new \yii\base\Exception("Failed to create directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
651
            }
652
        }
653
        try {
654 252
            return chmod($path, $mode);
655
        } catch (\Exception $e) {
656
            throw new \yii\base\Exception("Failed to change permissions for directory \"$path\": " . $e->getMessage(), $e->getCode(), $e);
657
        }
658
    }
659
660
    /**
661
     * Performs a simple comparison of file or directory names.
662
     *
663
     * Based on match_basename() from dir.c of git 1.8.5.3 sources.
664
     *
665
     * @param string $baseName file or directory name to compare with the pattern
666
     * @param string $pattern the pattern that $baseName will be compared against
667
     * @param int|bool $firstWildcard location of first wildcard character in the $pattern
668
     * @param int $flags pattern flags
669
     * @return bool whether the name matches against pattern
670
     */
671 75
    private static function matchBasename($baseName, $pattern, $firstWildcard, $flags)
672
    {
673 75
        if ($firstWildcard === false) {
674 11
            if ($pattern === $baseName) {
675 11
                return true;
676
            }
677 64
        } elseif ($flags & self::PATTERN_ENDSWITH) {
678
            /* "*literal" matching against "fooliteral" */
679 63
            $n = StringHelper::byteLength($pattern);
680 63
            if (StringHelper::byteSubstr($pattern, 1, $n) === StringHelper::byteSubstr($baseName, -$n, $n)) {
681
                return true;
682
            }
683
        }
684
685 75
        $matchOptions = [];
686 75
        if ($flags & self::PATTERN_CASE_INSENSITIVE) {
687 1
            $matchOptions['caseSensitive'] = false;
688
        }
689
690 75
        return StringHelper::matchWildcard($pattern, $baseName, $matchOptions);
691
    }
692
693
    /**
694
     * Compares a path part against a pattern with optional wildcards.
695
     *
696
     * Based on match_pathname() from dir.c of git 1.8.5.3 sources.
697
     *
698
     * @param string $path full path to compare
699
     * @param string $basePath base of path that will not be compared
700
     * @param string $pattern the pattern that path part will be compared against
701
     * @param int|bool $firstWildcard location of first wildcard character in the $pattern
702
     * @param int $flags pattern flags
703
     * @return bool whether the path part matches against pattern
704
     */
705 57
    private static function matchPathname($path, $basePath, $pattern, $firstWildcard, $flags)
706
    {
707
        // match with FNM_PATHNAME; the pattern has base implicitly in front of it.
708 57
        if (strncmp($pattern, '/', 1) === 0) {
709 54
            $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
710 54
            if ($firstWildcard !== false && $firstWildcard !== 0) {
711 54
                $firstWildcard--;
712
            }
713
        }
714
715 57
        $namelen = StringHelper::byteLength($path) - (empty($basePath) ? 0 : StringHelper::byteLength($basePath) + 1);
716 57
        $name = StringHelper::byteSubstr($path, -$namelen, $namelen);
717
718 57
        if ($firstWildcard !== 0) {
719 57
            if ($firstWildcard === false) {
720 56
                $firstWildcard = StringHelper::byteLength($pattern);
721
            }
722
            // if the non-wildcard part is longer than the remaining pathname, surely it cannot match.
723 57
            if ($firstWildcard > $namelen) {
724 3
                return false;
725
            }
726
727 57
            if (strncmp($pattern, $name, $firstWildcard)) {
0 ignored issues
show
Bug introduced by
It seems like $firstWildcard can also be of type true; however, parameter $length of strncmp() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

727
            if (strncmp($pattern, $name, /** @scrutinizer ignore-type */ $firstWildcard)) {
Loading history...
728 57
                return false;
729
            }
730 4
            $pattern = StringHelper::byteSubstr($pattern, $firstWildcard, StringHelper::byteLength($pattern));
0 ignored issues
show
Bug introduced by
It seems like $firstWildcard can also be of type true; however, parameter $start of yii\helpers\BaseStringHelper::byteSubstr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

730
            $pattern = StringHelper::byteSubstr($pattern, /** @scrutinizer ignore-type */ $firstWildcard, StringHelper::byteLength($pattern));
Loading history...
731 4
            $name = StringHelper::byteSubstr($name, $firstWildcard, $namelen);
732
733
            // 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.
734 4
            if (empty($pattern) && empty($name)) {
735 3
                return true;
736
            }
737
        }
738
739
        $matchOptions = [
740 2
            'filePath' => true
741
        ];
742 2
        if ($flags & self::PATTERN_CASE_INSENSITIVE) {
743
            $matchOptions['caseSensitive'] = false;
744
        }
745
746 2
        return StringHelper::matchWildcard($pattern, $name, $matchOptions);
747
    }
748
749
    /**
750
     * Scan the given exclude list in reverse to see whether pathname
751
     * should be ignored.  The first match (i.e. the last on the list), if
752
     * any, determines the fate.  Returns the element which
753
     * matched, or null for undecided.
754
     *
755
     * Based on last_exclude_matching_from_list() from dir.c of git 1.8.5.3 sources.
756
     *
757
     * @param string $basePath
758
     * @param string $path
759
     * @param array $excludes list of patterns to match $path against
760
     * @return array|null null or one of $excludes item as an array with keys: 'pattern', 'flags'
761
     * @throws InvalidArgumentException if any of the exclude patterns is not a string or an array with keys: pattern, flags, firstWildcard.
762
     */
763 76
    private static function lastExcludeMatchingFromList($basePath, $path, $excludes)
764
    {
765 76
        foreach (array_reverse($excludes) as $exclude) {
766 76
            if (is_string($exclude)) {
767
                $exclude = self::parseExcludePattern($exclude, false);
768
            }
769 76
            if (!isset($exclude['pattern']) || !isset($exclude['flags']) || !isset($exclude['firstWildcard'])) {
770
                throw new InvalidArgumentException('If exclude/include pattern is an array it must contain the pattern, flags and firstWildcard keys.');
771
            }
772 76
            if ($exclude['flags'] & self::PATTERN_MUSTBEDIR && !is_dir($path)) {
773
                continue;
774
            }
775
776 76
            if ($exclude['flags'] & self::PATTERN_NODIR) {
777 75
                if (self::matchBasename(basename($path), $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
778 73
                    return $exclude;
779
                }
780 74
                continue;
781
            }
782
783 57
            if (self::matchPathname($path, $basePath, $exclude['pattern'], $exclude['firstWildcard'], $exclude['flags'])) {
784 4
                return $exclude;
785
            }
786
        }
787
788 75
        return null;
789
    }
790
791
    /**
792
     * Processes the pattern, stripping special characters like / and ! from the beginning and settings flags instead.
793
     * @param string $pattern
794
     * @param bool $caseSensitive
795
     * @return array with keys: (string) pattern, (int) flags, (int|bool) firstWildcard
796
     * @throws InvalidArgumentException
797
     */
798 82
    private static function parseExcludePattern($pattern, $caseSensitive)
799
    {
800 82
        if (!is_string($pattern)) {
0 ignored issues
show
introduced by
The condition is_string($pattern) is always true.
Loading history...
801
            throw new InvalidArgumentException('Exclude/include pattern must be a string.');
802
        }
803
804
        $result = [
805 82
            'pattern' => $pattern,
806 82
            'flags' => 0,
807
            'firstWildcard' => false,
808
        ];
809
810 82
        if (!$caseSensitive) {
811 1
            $result['flags'] |= self::PATTERN_CASE_INSENSITIVE;
812
        }
813
814 82
        if (empty($pattern)) {
815
            return $result;
816
        }
817
818 82
        if (strncmp($pattern, '!', 1) === 0) {
819 1
            $result['flags'] |= self::PATTERN_NEGATIVE;
820 1
            $pattern = StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern));
821
        }
822 82
        if (StringHelper::byteLength($pattern) && StringHelper::byteSubstr($pattern, -1, 1) === '/') {
823
            $pattern = StringHelper::byteSubstr($pattern, 0, -1);
824
            $result['flags'] |= self::PATTERN_MUSTBEDIR;
825
        }
826 82
        if (strpos($pattern, '/') === false) {
827 81
            $result['flags'] |= self::PATTERN_NODIR;
828
        }
829 82
        $result['firstWildcard'] = self::firstWildcardInPattern($pattern);
830 82
        if (strncmp($pattern, '*', 1) === 0 && self::firstWildcardInPattern(StringHelper::byteSubstr($pattern, 1, StringHelper::byteLength($pattern))) === false) {
831 69
            $result['flags'] |= self::PATTERN_ENDSWITH;
832
        }
833 82
        $result['pattern'] = $pattern;
834
835 82
        return $result;
836
    }
837
838
    /**
839
     * Searches for the first wildcard character in the pattern.
840
     * @param string $pattern the pattern to search in
841
     * @return int|bool position of first wildcard character or false if not found
842
     */
843 82
    private static function firstWildcardInPattern($pattern)
844
    {
845 82
        $wildcards = ['*', '?', '[', '\\'];
846 82
        $wildcardSearch = function ($r, $c) use ($pattern) {
847 82
            $p = strpos($pattern, $c);
848
849 82
            return $r === false ? $p : ($p === false ? $r : min($r, $p));
850 82
        };
851
852 82
        return array_reduce($wildcards, $wildcardSearch, false);
853
    }
854
855
    /**
856
     * @param array $options raw options
857
     * @return array normalized options
858
     * @since 2.0.12
859
     */
860 179
    protected static function normalizeOptions(array $options)
861
    {
862 179
        if (!array_key_exists('caseSensitive', $options)) {
863 178
            $options['caseSensitive'] = true;
864
        }
865 179
        if (isset($options['except'])) {
866 62
            foreach ($options['except'] as $key => $value) {
867 62
                if (is_string($value)) {
868 62
                    $options['except'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
869
                }
870
            }
871
        }
872 179
        if (isset($options['only'])) {
873 80
            foreach ($options['only'] as $key => $value) {
874 80
                if (is_string($value)) {
875 80
                    $options['only'][$key] = self::parseExcludePattern($value, $options['caseSensitive']);
876
                }
877
            }
878
        }
879
880 179
        return $options;
881
    }
882
883
    /**
884
     * Changes the Unix user and/or group ownership of a file or directory, and optionally the mode.
885
     * Note: This function will not work on remote files as the file to be examined must be accessible
886
     * via the server's filesystem.
887
     * Note: On Windows, this function fails silently when applied on a regular file.
888
     * @param string $path the path to the file or directory.
889
     * @param string|array|int|null $ownership the user and/or group ownership for the file or directory.
890
     * When $ownership is a string, the format is 'user:group' where both are optional. E.g.
891
     * 'user' or 'user:' will only change the user,
892
     * ':group' will only change the group,
893
     * 'user:group' will change both.
894
     * When $owners is an index array the format is [0 => user, 1 => group], e.g. `[$myUser, $myGroup]`.
895
     * It is also possible to pass an associative array, e.g. ['user' => $myUser, 'group' => $myGroup].
896
     * In case $owners is an integer it will be used as user id.
897
     * If `null`, an empty array or an empty string is passed, the ownership will not be changed.
898
     * @param int|null $mode the permission to be set for the file or directory.
899
     * If `null` is passed, the mode will not be changed.
900
     *
901
     * @since 2.0.43
902
     */
903 90
    public static function changeOwnership($path, $ownership, $mode = null)
904
    {
905 90
        if (!file_exists((string)$path)) {
906 1
            throw new InvalidArgumentException('Unable to change ownership, "' . $path . '" is not a file or directory.');
907
        }
908
909 89
        if (empty($ownership) && $ownership !== 0 && $mode === null) {
910 84
            return;
911
        }
912
913 5
        $user = $group = null;
914 5
        if (!empty($ownership) || $ownership === 0 || $ownership === '0') {
915 4
            if (is_int($ownership)) {
916
                $user = $ownership;
917 4
            } elseif (is_string($ownership)) {
918 1
                $ownerParts = explode(':', $ownership);
919 1
                $user = $ownerParts[0];
920 1
                if (count($ownerParts) > 1) {
921 1
                    $group = $ownerParts[1];
922
                }
923 3
            } elseif (is_array($ownership)) {
0 ignored issues
show
introduced by
The condition is_array($ownership) is always true.
Loading history...
924 2
                $ownershipIsIndexed = ArrayHelper::isIndexed($ownership);
925 2
                $user = ArrayHelper::getValue($ownership, $ownershipIsIndexed ? 0 : 'user');
926 2
                $group = ArrayHelper::getValue($ownership, $ownershipIsIndexed ? 1 : 'group');
927
            } else {
928 1
                throw new InvalidArgumentException('$ownership must be an integer, string, array, or null.');
929
            }
930
        }
931
932 4
        if ($mode !== null) {
933 1
            if (!is_int($mode)) {
0 ignored issues
show
introduced by
The condition is_int($mode) is always true.
Loading history...
934 1
                throw new InvalidArgumentException('$mode must be an integer or null.');
935
            }
936
            if (!chmod($path, $mode)) {
937
                throw new Exception('Unable to change mode of "' . $path . '" to "0' . decoct($mode) . '".');
938
            }
939
        }
940 3
        if ($user !== null && $user !== '') {
941 2
            if (is_numeric($user)) {
942
                $user = (int) $user;
943 2
            } elseif (!is_string($user)) {
944 1
                throw new InvalidArgumentException('The user part of $ownership must be an integer, string, or null.');
945
            }
946 1
            if (!chown($path, $user)) {
947
                throw new Exception('Unable to change user ownership of "' . $path . '" to "' . $user . '".');
948
            }
949
        }
950 1
        if ($group !== null && $group !== '') {
951 1
            if (is_numeric($group)) {
952
                $group = (int) $group;
953 1
            } elseif (!is_string($group)) {
954 1
                throw new InvalidArgumentException('The group part of $ownership must be an integer, string or null.');
955
            }
956
            if (!chgrp($path, $group)) {
957
                throw new Exception('Unable to change group ownership of "' . $path . '" to "' . $group . '".');
958
            }
959
        }
960
    }
961
}
962