FileUtils::getPath()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 6
nc 5
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace WebThumbnailer\Utils;
6
7
class FileUtils
8
{
9
    /** @var string Path to resources folder. */
10
    public const RESOURCES_PATH =
11
        __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR;
12
13
    /**
14
     * Build the path from all given folders, with a trailing /.
15
     * It will stay a relative or absolute path depending on what's provided.
16
     *
17
    // phpcs:ignore Gskema.Sniffs.CompositeCodeElement.FqcnMethodSniff
18
     * @param string[] $args Suite of path/folders.
19
     *
20
     * @return string|false Path with proper directory separators, false if it doesn't exist.
21
     */
22
    // phpcs:ignore Gskema.Sniffs.CompositeCodeElement.FqcnMethodSniff
23
    public static function getPath(string ...$args)
24
    {
25
        $out = '';
26
        if (empty($args)) {
27
            return false;
28
        }
29
        foreach ($args as $arg) {
30
            $out .= rtrim(rtrim($arg, '/'), '\\') . DIRECTORY_SEPARATOR;
31
        }
32
        return is_dir($out) ? $out : false;
33
    }
34
35
    /**
36
     * Remove a directory and its content.
37
     *
38
     * @param string $path to delete.
39
     *
40
     * @return bool True if the rm was successful, false otherwise or if the path is invalid.
41
     */
42
    public static function rmdir(string $path): bool
43
    {
44
        if (empty($path) || $path == '/' || !static::getPath($path)) {
45
            return false;
46
        }
47
48
        foreach (
49
            new \RecursiveIteratorIterator(
50
                new \RecursiveDirectoryIterator(
51
                    $path,
52
                    \FilesystemIterator::SKIP_DOTS |
53
                     \FilesystemIterator::UNIX_PATHS
54
                ),
55
                \RecursiveIteratorIterator::CHILD_FIRST
56
            ) as $value
57
        ) {
58
            $value->isDir() ? rmdir($value->getRealPath()) : unlink($value->getRealPath());
59
        }
60
61
        return rmdir($path);
62
    }
63
}
64