Passed
Pull Request — master (#39)
by Sergei
01:52
created

FileHelper   F

Complexity

Total Complexity 85

Size/Duplication

Total Lines 478
Duplicated Lines 0 %

Test Coverage

Coverage 94.9%

Importance

Changes 6
Bugs 1 Features 0
Metric Value
wmc 85
eloc 147
c 6
b 1
f 0
dl 0
loc 478
ccs 149
cts 157
cp 0.949
rs 2

14 Methods

Rating   Name   Duplication   Size   Complexity  
A assertNotSelfDirectory() 0 4 3
A openFile() 0 9 2
A openDirectory() 0 9 2
C normalizePath() 0 31 14
B findDirectories() 0 31 10
C copyDirectory() 0 47 15
B clearDirectory() 0 16 7
A unlink() 0 21 6
B findFiles() 0 31 10
A createDirectory() 0 19 5
A modifiedTime() 0 3 1
A isEmptyDirectory() 0 7 2
A removeDirectory() 0 12 3
A lastModifiedTime() 0 28 5

How to fix   Complexity   

Complex Class

Complex classes like FileHelper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FileHelper, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Files;
6
7
use Exception;
8
use FilesystemIterator;
9
use InvalidArgumentException;
10
use LogicException;
11
use RecursiveDirectoryIterator;
12
use RecursiveIteratorIterator;
13
use RuntimeException;
14
use Throwable;
15
16
/**
17
 * FileHelper provides useful methods to manage files and directories
18
 */
19
class FileHelper
20
{
21
    /**
22
     * Opens a file or URL.
23
     *
24
     * This method is similar to the PHP `fopen()` function, except that it suppresses the `E_WARNING`
25
     * level error and throws the `\RuntimeException` exception if it can't open the file.
26
     *
27
     * @param string $filename The file or URL.
28
     * @param string $mode The type of access.
29
     * @param bool $useIncludePath Whether to search for a file in the include path.
30
     * @param resource|null $context The stream context or `null`.
31
     *
32
     * @throws RuntimeException If the file could not be opened.
33
     *
34
     * @return resource The file pointer resource.
35
     *
36
     * @psalm-suppress PossiblyNullArgument
37
     */
38 3
    public static function openFile(string $filename, string $mode, bool $useIncludePath = false, $context = null)
39
    {
40 3
        $filePointer = @fopen($filename, $mode, $useIncludePath, $context);
41
42 3
        if ($filePointer === false) {
43 1
            throw new RuntimeException("The file \"{$filename}\" could not be opened.");
44
        }
45
46 2
        return $filePointer;
47
    }
48
49
    /**
50
     * Creates a new directory.
51
     *
52
     * This method is similar to the PHP `mkdir()` function except that it uses `chmod()` to set the permission of the
53
     * created directory in order to avoid the impact of the `umask` setting.
54
     *
55
     * @param string $path path of the directory to be created.
56
     * @param int $mode the permission to be set for the created directory.
57
     *
58
     * @return bool whether the directory is created successfully.
59
     */
60 52
    public static function createDirectory(string $path, int $mode = 0775): bool
61
    {
62 52
        $path = static::normalizePath($path);
63
64
        try {
65 52
            if (!mkdir($path, $mode, true) && !is_dir($path)) {
66 52
                return false;
67
            }
68 2
        } catch (Exception $e) {
69 2
            if (!is_dir($path)) {
70 1
                throw new RuntimeException(
71 1
                    'Failed to create directory "' . $path . '": ' . $e->getMessage(),
72 1
                    (int)$e->getCode(),
73
                    $e
74
                );
75
            }
76
        }
77
78 52
        return chmod($path, $mode);
79
    }
80
81
    /**
82
     * Normalizes a file/directory path.
83
     *
84
     * The normalization does the following work:
85
     *
86
     * - Convert all directory separators into `/` (e.g. "\a/b\c" becomes "/a/b/c")
87
     * - Remove trailing directory separators (e.g. "/a/b/c/" becomes "/a/b/c")
88
     * - Turn multiple consecutive slashes into a single one (e.g. "/a///b/c" becomes "/a/b/c")
89
     * - Remove ".." and "." based on their meanings (e.g. "/a/./b/../c" becomes "/a/c")
90
     *
91
     * @param string $path the file/directory path to be normalized
92
     *
93
     * @return string the normalized file/directory path
94
     */
95 52
    public static function normalizePath(string $path): string
96
    {
97 52
        $isWindowsShare = strpos($path, '\\\\') === 0;
98
99 52
        if ($isWindowsShare) {
100 1
            $path = substr($path, 2);
101
        }
102
103 52
        $path = rtrim(strtr($path, '/\\', '//'), '/');
104
105 52
        if (strpos('/' . $path, '/.') === false && strpos($path, '//') === false) {
106 52
            return $isWindowsShare ? "\\\\$path" : $path;
107
        }
108
109 1
        $parts = [];
110
111 1
        foreach (explode('/', $path) as $part) {
112 1
            if ($part === '..' && !empty($parts) && end($parts) !== '..') {
113 1
                array_pop($parts);
114 1
            } elseif ($part !== '.' && ($part !== '' || empty($parts))) {
115 1
                $parts[] = $part;
116
            }
117
        }
118
119 1
        $path = implode('/', $parts);
120
121 1
        if ($isWindowsShare) {
122 1
            $path = '\\\\' . $path;
123
        }
124
125 1
        return $path === '' ? '.' : $path;
126
    }
127
128
    /**
129
     * Removes a directory (and all its content) recursively.
130
     *
131
     * @param string $directory the directory to be deleted recursively.
132
     * @param array $options options for directory remove ({@see clearDirectory()}).
133
     */
134 52
    public static function removeDirectory(string $directory, array $options = []): void
135
    {
136
        try {
137 52
            static::clearDirectory($directory, $options);
138 1
        } catch (InvalidArgumentException $e) {
139 1
            return;
140
        }
141
142 52
        if (is_link($directory)) {
143 2
            self::unlink($directory);
144
        } else {
145 52
            rmdir($directory);
146
        }
147 52
    }
148
149
    /**
150
     * Clear all directory content.
151
     *
152
     * @param string $directory the directory to be cleared.
153
     * @param array $options options for directory clear . Valid options are:
154
     *
155
     * - traverseSymlinks: boolean, whether symlinks to the directories should be traversed too.
156
     *   Defaults to `false`, meaning the content of the symlinked directory would not be deleted.
157
     *   Only symlink would be removed in that default case.
158
     *
159
     * @throws InvalidArgumentException if unable to open directory
160
     */
161 52
    public static function clearDirectory(string $directory, array $options = []): void
162
    {
163 52
        $handle = static::openDirectory($directory);
164 52
        if (!empty($options['traverseSymlinks']) || !is_link($directory)) {
165 52
            while (($file = readdir($handle)) !== false) {
166 52
                if ($file === '.' || $file === '..') {
167 52
                    continue;
168
                }
169 37
                $path = $directory . '/' . $file;
170 37
                if (is_dir($path)) {
171 36
                    self::removeDirectory($path, $options);
172
                } else {
173 27
                    self::unlink($path);
174
                }
175
            }
176 52
            closedir($handle);
177
        }
178 52
    }
179
180
    /**
181
     * Removes a file or symlink in a cross-platform way.
182
     *
183
     * @param string $path
184
     *
185
     * @return bool
186
     */
187 31
    public static function unlink(string $path): bool
188
    {
189 31
        $isWindows = DIRECTORY_SEPARATOR === '\\';
190
191 31
        if (!$isWindows) {
192 31
            return unlink($path);
193
        }
194
195
        if (is_link($path)) {
196
            try {
197
                return unlink($path);
198
            } catch (Throwable $e) {
199
                return rmdir($path);
200
            }
201
        }
202
203
        if (file_exists($path) && !is_writable($path)) {
204
            chmod($path, 0777);
205
        }
206
207
        return unlink($path);
208
    }
209
210
    /**
211
     * Tells whether the path is a empty directory
212
     *
213
     * @param string $path
214
     *
215
     * @return bool
216
     */
217 1
    public static function isEmptyDirectory(string $path): bool
218
    {
219 1
        if (!is_dir($path)) {
220 1
            return false;
221
        }
222
223 1
        return !(new FilesystemIterator($path))->valid();
224
    }
225
226
    /**
227
     * Copies a whole directory as another one.
228
     *
229
     * The files and sub-directories will also be copied over.
230
     *
231
     * @param string $source the source directory.
232
     * @param string $destination the destination directory.
233
     * @param array $options options for directory copy. Valid options are:
234
     *
235
     * - dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
236
     * - fileMode: integer, the permission to be set for newly copied files. Defaults to the current environment
237
     *   setting.
238
     * - filter: a filter to apply while copying files. It should be an instance of {@see PathMatcherInterface}.
239
     * - recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true.
240
     * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file. If the callback
241
     *   returns false, the copy operation for the sub-directory or file will be cancelled. The signature of the
242
     *   callback should be: `function ($from, $to)`, where `$from` is the sub-directory or file to be copied from,
243
     *   while `$to` is the copy target.
244
     * - afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied.
245
     *   The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or file
246
     *   copied from, while `$to` is the copy target.
247
     * - copyEmptyDirectories: boolean, whether to copy empty directories. Set this to false to avoid creating
248
     *   directories that do not contain files. This affects directories that do not contain files initially as well as
249
     *   directories that do not contain files at the target destination because files have been filtered via `only` or
250
     *   `except`. Defaults to true.
251
     *
252
     * @throws InvalidArgumentException if unable to open directory
253
     * @throws Exception
254
     *
255
     * @psalm-param array{
256
     *   dirMode?: int,
257
     *   fileMode?: int,
258
     *   filter?: \Yiisoft\Files\PathMatcher\PathMatcherInterface,
259
     *   recursive?: bool,
260
     *   beforeCopy?: callable,
261
     *   afterCopy?: callable,
262
     *   copyEmptyDirectories?: bool,
263
     * } $options
264
     */
265 12
    public static function copyDirectory(string $source, string $destination, array $options = []): void
266
    {
267 12
        $source = static::normalizePath($source);
268 12
        $destination = static::normalizePath($destination);
269
270 12
        static::assertNotSelfDirectory($source, $destination);
271
272 10
        $destinationExists = is_dir($destination);
273
        if (
274 10
            !$destinationExists &&
275 10
            (!isset($options['copyEmptyDirectories']) || $options['copyEmptyDirectories'])
276
        ) {
277 6
            static::createDirectory($destination, $options['dirMode'] ?? 0775);
278 6
            $destinationExists = true;
279
        }
280
281 10
        $handle = static::openDirectory($source);
282
283 9
        if (!isset($options['basePath'])) {
284 9
            $options['basePath'] = realpath($source);
285
        }
286
287 9
        while (($file = readdir($handle)) !== false) {
288 9
            if ($file === '.' || $file === '..') {
289 9
                continue;
290
            }
291
292 7
            $from = $source . '/' . $file;
293 7
            $to = $destination . '/' . $file;
294
295 7
            if (!isset($options['filter']) || $options['filter']->match($from)) {
296 7
                if (is_file($from)) {
297 7
                    if (!$destinationExists) {
298 2
                        static::createDirectory($destination, $options['dirMode'] ?? 0775);
299 2
                        $destinationExists = true;
300
                    }
301 7
                    copy($from, $to);
302 7
                    if (isset($options['fileMode'])) {
303 7
                        chmod($to, $options['fileMode']);
304
                    }
305 6
                } elseif (!isset($options['recursive']) || $options['recursive']) {
306 5
                    static::copyDirectory($from, $to, $options);
307
                }
308
            }
309
        }
310
311 9
        closedir($handle);
312 9
    }
313
314
    /**
315
     * Check copy it self directory.
316
     *
317
     * @param string $source
318
     * @param string $destination
319
     *
320
     * @throws InvalidArgumentException
321
     */
322 12
    private static function assertNotSelfDirectory(string $source, string $destination): void
323
    {
324 12
        if ($source === $destination || strpos($destination, $source . '/') === 0) {
325 2
            throw new InvalidArgumentException('Trying to copy a directory to itself or a subdirectory.');
326
        }
327 10
    }
328
329
    /**
330
     * Open directory handle.
331
     *
332
     * @param string $directory
333
     *
334
     * @throws InvalidArgumentException
335
     *
336
     * @return resource
337
     */
338 52
    private static function openDirectory(string $directory)
339
    {
340 52
        $handle = @opendir($directory);
341
342 52
        if ($handle === false) {
343 3
            throw new InvalidArgumentException("Unable to open directory: $directory");
344
        }
345
346 52
        return $handle;
347
    }
348
349
    /**
350
     * Returns the last modification time for the given path.
351
     *
352
     * If the path is a directory, any nested files/directories will be checked as well.
353
     *
354
     * @param string ...$paths the directory to be checked
355
     *
356
     * @throws LogicException when path not set
357
     *
358
     * @return int Unix timestamp representing the last modification time
359
     */
360 2
    public static function lastModifiedTime(string ...$paths): int
361
    {
362 2
        if (empty($paths)) {
363 1
            throw new LogicException('Path is required.');
364
        }
365
366 1
        $times = [];
367
368 1
        foreach ($paths as $path) {
369 1
            $times[] = static::modifiedTime($path);
370
371 1
            if (is_file($path)) {
372 1
                continue;
373
            }
374
375
            /** @var iterable<string, string> $iterator */
376 1
            $iterator = new RecursiveIteratorIterator(
377 1
                new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
378 1
                RecursiveIteratorIterator::SELF_FIRST
379
            );
380
381 1
            foreach ($iterator as $p => $info) {
382 1
                $times[] = static::modifiedTime($p);
383
            }
384
        }
385
386
        /** @psalm-suppress ArgumentTypeCoercion */
387 1
        return max($times);
388
    }
389
390 1
    private static function modifiedTime(string $path): int
391
    {
392 1
        return (int)filemtime($path);
393
    }
394
395
    /**
396
     * Returns the directories found under the specified directory and subdirectories.
397
     *
398
     * @param string $directory the directory under which the files will be looked for.
399
     * @param array $options options for directory searching. Valid options are:
400
     *
401
     * - filter: a filter to apply while looked directories. It should be an instance of {@see PathMatcherInterface}.
402
     * - recursive: boolean, whether the subdirectories should also be looked for. Defaults to `true`.
403
     *
404
     * @psalm-param array{
405
     *   filter?: \Yiisoft\Files\PathMatcher\PathMatcherInterface,
406
     *   recursive?: bool,
407
     * } $options
408
     *
409
     * @throws InvalidArgumentException if the directory is invalid.
410
     *
411
     * @return string[] directories found under the directory, in no particular order.
412
     * Ordering depends on the files system used.
413
     */
414 5
    public static function findDirectories(string $directory, array $options = []): array
415
    {
416 5
        if (!is_dir($directory)) {
417 1
            throw new InvalidArgumentException("The \"directory\" argument must be a directory: $directory");
418
        }
419 4
        $directory = static::normalizePath($directory);
420
421 4
        $result = [];
422
423 4
        $handle = static::openDirectory($directory);
424 4
        while (false !== $file = readdir($handle)) {
425 4
            if ($file === '.' || $file === '..') {
426 4
                continue;
427
            }
428
429 4
            $path = $directory . '/' . $file;
430 4
            if (is_file($path)) {
431 3
                continue;
432
            }
433
434 4
            if (!isset($options['filter']) || $options['filter']->match($path)) {
435 4
                $result[] = $path;
436
            }
437
438 4
            if (!isset($options['recursive']) || $options['recursive']) {
439 3
                $result = array_merge($result, static::findDirectories($path, $options));
440
            }
441
        }
442 4
        closedir($handle);
443
444 4
        return $result;
445
    }
446
447
    /**
448
     * Returns the files found under the specified directory and subdirectories.
449
     *
450
     * @param string $directory the directory under which the files will be looked for.
451
     * @param array $options options for file searching. Valid options are:
452
     *
453
     * - filter: a filter to apply while looked files. It should be an instance of {@see PathMatcherInterface}.
454
     * - recursive: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`.
455
     *
456
     * @psalm-param array{
457
     *   filter?: \Yiisoft\Files\PathMatcher\PathMatcherInterface,
458
     *   recursive?: bool,
459
     * } $options
460
     *
461
     * @throws InvalidArgumentException if the dir is invalid.
462
     *
463
     * @return array files found under the directory, in no particular order.
464
     * Ordering depends on the files system used.
465
     */
466 4
    public static function findFiles(string $directory, array $options = []): array
467
    {
468 4
        if (!is_dir($directory)) {
469
            throw new InvalidArgumentException("The \"directory\" argument must be a directory: $directory");
470
        }
471 4
        $directory = static::normalizePath($directory);
472
473 4
        $result = [];
474
475 4
        $handle = static::openDirectory($directory);
476 4
        while (false !== $file = readdir($handle)) {
477 4
            if ($file === '.' || $file === '..') {
478 4
                continue;
479
            }
480
481 4
            $path = $directory . '/' . $file;
482
483 4
            if (is_file($path)) {
484 4
                if (!isset($options['filter']) || $options['filter']->match($path)) {
485 4
                    $result[] = $path;
486
                }
487 4
                continue;
488
            }
489
490 4
            if (!isset($options['recursive']) || $options['recursive']) {
491 3
                $result = array_merge($result, static::findFiles($path, $options));
492
            }
493
        }
494 4
        closedir($handle);
495
496 4
        return $result;
497
    }
498
}
499