Completed
Push — master ( b31514...603a9f )
by Changwan
06:16
created

PathLoader::test()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Wandu\Config\Loader;
3
4
use DirectoryIterator;
5
use Wandu\Config\Contracts\Loader;
6
7
class PathLoader implements Loader
8
{
9
    /** @var \Wandu\Config\Contracts\Loader[] */
10
    protected $loaders;
11
    
12
    /** @var string */
13
    protected $pattern;
14
    
15 2
    public function __construct(array $loaders = [], string $pattern = '~^[a-z_][a-z0-9_]*$~')
16
    {
17 2
        $this->loaders = $loaders;
18 2
        $this->pattern = $pattern;
19 2
    }
20
21
    /**
22
     * {@inheritdoc}
23
     */
24 2
    public function test(string $path): bool
25
    {
26 2
        return is_dir($path);
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32 2
    public function load(string $path)
33
    {
34 2
        $configToReturn = [];
35 2
        foreach (new DirectoryIterator($path) as $file) {
36 2
            $filename = $file->getFilename();
37 2
            if ($filename === '.' || $filename === '..') continue;
38 2
            if ($file->isFile()) {
39 2
                $name = $file->getBasename("." . $file->getExtension());
40 2
                foreach ($this->loaders as $loader) {
41 2
                    if ($loader->test($file->getRealPath())) {
42 2
                        if ($config = $loader->load($file->getRealPath())) {
43 2
                            $configToReturn[$name] = $config;
44
                        }
45
                    }
46
                }
47
            } else {
48 1
                if (preg_match($this->pattern, $filename)) {
49 2
                    $configToReturn[$filename] = $this->load($file->getRealPath());
50
                }
51
            }
52
        }
53 2
        return $configToReturn;
54
    }
55
}
56