Passed
Pull Request — master (#41)
by Alexander
02:19
created

FileHelper::ensureDirectory()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 24
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4.0092

Importance

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