Passed
Pull Request — master (#38)
by Sergei
09:50
created

FileHelper   F

Complexity

Total Complexity 65

Size/Duplication

Total Lines 370
Duplicated Lines 0 %

Test Coverage

Coverage 95.8%

Importance

Changes 6
Bugs 1 Features 0
Metric Value
wmc 65
eloc 110
c 6
b 1
f 0
dl 0
loc 370
ccs 114
cts 119
cp 0.958
rs 3.2

12 Methods

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