Passed
Push — master ( 32cffc...62a894 )
by Bence
04:17
created

RecursiveFileListing::recursiveScan()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 9
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
eloc 8
nc 5
nop 1
dl 0
loc 9
ccs 0
cts 9
cp 0
crap 56
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
namespace CSFCloud\Files;
4
5
use Exception;
6
7
class RecursiveFileListing {
8
9
    private $root_dir;
10
    private $files;
11
    private $filters = [];
12
13
    public function __construct (string $dir) {
14
        if (!is_dir($dir)) {
15
            throw new Exception("Directory required");
16
        }
17
18
        $this->root_dir = $dir;
19
    }
20
21
    public function addFilter (string $regex) {
22
        $this->filters[] = $regex;
23
    }
24
25
    public function clearFilters () {
26
        $this->filters = [];
27
    }
28
29
    public function scan () : array {
30
        $this->files = [];
31
        $this->recursiveScan($this->root_dir);
32
        sort($this->files);
33
        return $this->files;
34
    }
35
36
    private function recursiveScan (string $dir) {
37
        $files = scandir($dir);
38
        foreach ($files as $filename) {
39
            if ($filename !== "." && $filename !== "..") {
40
                $file_path = $dir . "/" . $filename;
41
                if (is_file($file_path) && $this->isFileOk($file_path)) {
42
                    $this->files[] = $file_path;
43
                } else if (is_dir($file_path)) {
44
                    $this->recursiveScan($file_path);
45
                }
46
            }
47
        }
48
    }
49
50
    private function isFileOk (string $path) : bool {
51
        if (count($this->filters) == 0) {
52
            return true;
53
        }
54
55
        foreach ($this->filters as $filter) {
56
            if (preg_match($filter, $path)) {
57
                return true;
58
            }
59
        }
60
61
        return false;
62
    }
63
64
}