Passed
Pull Request — master (#86)
by
unknown
02:54
created

FileSystemUtils::collectGlobs()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 15
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 27
rs 9.4555
1
<?php
2
/**
3
 * Copyright © Vaimo Group. All rights reserved.
4
 * See LICENSE_VAIMO.txt for license details.
5
 */
6
namespace Vaimo\ComposerPatches\Utils;
7
8
class FileSystemUtils
9
{
10
    public function collectFilePathsRecursively($rootPath, $pattern)
11
    {
12
        if (strpos($rootPath, '*') !== false || strpos($rootPath, '?') !== false) {
13
            $paths = $this->collectGlobs($rootPath, $pattern);
14
        } else {
15
            $paths = $this->collectPathsRecursively($rootPath, $pattern);
16
        }
17
18
        return array_filter($paths, function ($item) {
19
            return is_file($item);
20
        });
21
    }
22
23
    public function collectGlobs($rootPath, $pattern)
24
    {
25
        $iterator = new \GlobIterator($rootPath);
26
27
        $files = array();
28
29
        foreach ($iterator as $info) {
30
            if($info->isDir()) {
31
                $files = [...$files, ...$this->collectPathsRecursively($info->getRealPath(), $pattern)];
32
                continue;
33
            }
34
35
            if (!$info->isFile() || !preg_match($pattern, $info->getRealPath())) {
36
                continue;
37
            }
38
39
            $path = $info->getRealPath();
40
            $files[$path] = $path;
41
        }
42
43
        $sequence = array_keys($files);
44
45
        natsort($sequence);
46
47
        return array_replace(
48
            array_flip($sequence),
49
            $files
50
        );
51
    }
52
53
    public function collectPathsRecursively($rootPath, $pattern)
54
    {
55
        if (!is_dir($rootPath)) {
56
            return array();
57
        }
58
59
        $directoryIterator = new \RecursiveDirectoryIterator(
60
            $rootPath,
61
            \RecursiveDirectoryIterator::FOLLOW_SYMLINKS
62
        );
63
64
        $recursiveIterator = new \RecursiveIteratorIterator($directoryIterator);
65
66
        $filesIterator = new \RegexIterator(
67
            $recursiveIterator,
68
            $pattern,
69
            \RecursiveRegexIterator::GET_MATCH
70
        );
71
72
        $files = array();
73
74
        foreach ($filesIterator as $info) {
75
            $path = reset($info);
76
            $files[substr($path, strlen($rootPath) + 1)] = $path;
77
        }
78
79
        $sequence = array_keys($files);
80
81
        natsort($sequence);
82
83
        return array_replace(
84
            array_flip($sequence),
85
            $files
86
        );
87
    }
88
}
89