Passed
Push — master ( 939a6b...8ca850 )
by Bence
03:55
created

RecursiveFileListing   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 57
ccs 34
cts 34
cp 1
rs 10
c 0
b 0
f 0
wmc 16

6 Methods

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