FolderReader::result()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Maestriam\FileSystem\Foundation;
4
5
abstract class FolderReader
6
{
7
    static private array $result = [];
8
9
    static public function read(string $path, int $level) : array
10
    {        
11
        if (! is_dir($path)) return [];
12
        
13
        self::scan($path, 1, $level);
14
        
15
        $result = self::result();
16
        
17
        self::reset();
18
19
        return $result;
20
    }
21
22
    static private function result() : array
23
    {
24
        return self::$result;
25
    }
26
27
    static private function reset()
28
    {
29
        self::$result = [];
30
    }
31
32
    static private function scan(string $path, int $step, int $level) : void
33
    {
34
        $items  = array_diff(scandir($path), array('.', '..'));        
35
        
36
        foreach($items as $item) {
37
38
            $folder = "$path/$item"; 
39
40
            if (! is_dir($folder)) {
41
                continue;
42
            }
43
            
44
            if (is_dir($folder) && $step < $level) {
45
                self::scan($folder, $step+1, $level);
46
            }
47
48
            if ($step == $level) {
49
                self::add($folder, $level);
50
            }
51
        }
52
    }
53
    
54
    static private function add(string $path, int $level) : void
55
    {
56
        $folder = self::prepare($path, $level);
57
        
58
        array_push(self::$result, $folder);
59
    }
60
61
    static private function prepare(string $path, int $level) : string
62
    {
63
        $path = str_replace(DS, '/', $path);
64
65
        $pieces = explode('/', $path);
66
        $pieces = array_splice($pieces, - $level);
67
68
        return implode('/', $pieces);
69
    }
70
}