Psr4List::files()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 9
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 13
ccs 3
cts 3
cp 1
crap 1
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Koriym\Psr4List;
6
7
use FilesystemIterator;
8
use Generator;
9
use RecursiveDirectoryIterator;
10
use RecursiveIteratorIterator;
11
use RecursiveRegexIterator;
12
use RegexIterator;
13
14
use function class_exists;
15
use function interface_exists;
16
use function str_replace;
17 2
use function strlen;
18
use function substr;
19 2
20
class Psr4List
21
{
22
    /**
23
     * @param string $prefix
24
     * @param string $path
25
     *
26
     * @return Generator<array{0: class-string, 1: string}>
27
     */
28 2
    public function __invoke($prefix, $path): Generator
29
    {
30 2
        return $this->invoke($prefix, $path);
31
    }
32 2
33 2
    /**
34 2
     * @param string $prefix
35 2
     * @param string $path
36 1
     *
37
     * @return Generator<array{0: string, 1: string}>
38
     */
39 1
    private function invoke($prefix, $path): Generator
40
    {
41 2
        foreach ($this->files($path) as $item) {
42
            $file = str_replace('\\', '/', $item->getPathname());
43
            $namePath = str_replace('/', '\\', substr(substr($file, strlen($path) + 1), 0, -4));
44
            $class = $prefix . '\\' . $namePath;
45
            if (! class_exists($class) && ! interface_exists($class)) {
46 2
                continue;
47
            }
48 2
49 2
            yield [$class, $file];
50 2
        }
51 2
    }
52 2
53 2
    /** @param string $dir */
54
    private function files($dir): SortingIterator
55 2
    {
56
        return new SortingIterator(
57 2
            new RegexIterator(
58 2
                new RecursiveIteratorIterator(
59
                    new RecursiveDirectoryIterator(
60
                        $dir,
61
                        FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::SKIP_DOTS
62
                    ),
63
                    RecursiveIteratorIterator::LEAVES_ONLY
64
                ),
65
                '/^.+\.php$/',
66
                RecursiveRegexIterator::MATCH
67
            )
68
        );
69
    }
70
}
71