Test Failed
Pull Request — master (#85)
by Ruud
03:31
created

FileLocator   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 26
dl 0
loc 65
rs 10
c 0
b 0
f 0
wmc 14

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B findFileForClass() 0 25 8
A findAllClasses() 0 20 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Metadata\Driver;
6
7
use function file_exists;
8
use function str_replace;
9
use function strpos;
10
use function substr;
11
12
class FileLocator implements AdvancedFileLocatorInterface
13
{
14
    /**
15
     * @var string[]
16
     */
17
    private $dirs;
18
19
    /**
20
     * @param string[] $dirs
21
     */
22
    public function __construct(array $dirs)
23
    {
24
        $this->dirs = $dirs;
25
    }
26
27
    public function findFileForClass(\ReflectionClass $class, string $extension): ?string
28
    {
29
        foreach ($this->dirs as $prefix => $dir) {
30
            if ('' !== $prefix && 0 !== strpos($class->getNamespaceName(), $prefix)) {
31
                continue;
32
            }
33
34
            $len = '' === $prefix ? 0 : strlen($prefix) + 1;
35
            $fqcn = str_replace('\\', '.', substr($class->name, $len));
36
37
            while (true) {
38
                $path = $dir . '/' . $fqcn . '.' . $extension;
39
                if (file_exists($path)) {
40
                    return $path;
41
                }
42
43
                if (false === strpos($fqcn, '.')) {
44
                    break;
45
                }
46
47
                $fqcn = substr($fqcn, 0, strrpos($fqcn, '.'));
48
            }
49
        }
50
51
        return null;
52
    }
53
54
    /**
55
     * {@inheritDoc}
56
     */
57
    public function findAllClasses(string $extension): array
58
    {
59
        $classes = [];
60
        foreach ($this->dirs as $prefix => $dir) {
61
            /** @var \RecursiveIteratorIterator|\SplFileInfo[] $iterator */
62
            $iterator = new \RecursiveIteratorIterator(
63
                new \RecursiveDirectoryIterator($dir),
64
                \RecursiveIteratorIterator::LEAVES_ONLY
65
            );
66
            $nsPrefix = '' !== $prefix ? $prefix . '\\' : '';
67
            foreach ($iterator as $file) {
68
                if (($fileName = $file->getBasename('.' . $extension)) === $file->getBasename()) {
69
                    continue;
70
                }
71
72
                $classes[] = $nsPrefix . str_replace('.', '\\', $fileName);
73
            }
74
        }
75
76
        return $classes;
77
    }
78
}
79