Passed
Pull Request — master (#60)
by Ondřej
02:41
created

prepareBlacklistPatterns()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
ccs 8
cts 8
cp 1
cc 3
eloc 7
nc 3
nop 1
crap 3
1
<?php
2
3
namespace ComposerRequireChecker\FileLocator;
4
5
use Traversable;
6
7
final class LocateAllFilesByExtension
8
{
9 3
    public function __invoke(Traversable $directories, string $fileExtension, ?array $blacklist): Traversable
10
    {
11 3
        foreach ($directories as $directory) {
12 2
            yield from $this->filterFilesByExtension(
13 2
                new \RecursiveIteratorIterator(
14 2
                    new \RecursiveDirectoryIterator($directory),
15 2
                    \RecursiveIteratorIterator::LEAVES_ONLY
16
                ),
17 2
                $fileExtension,
18 2
                $blacklist
19
            );
20
        }
21 3
    }
22
23 2
    private function filterFilesByExtension(Traversable $files, string $fileExtension, ?array $blacklist): Traversable
24
    {
25 2
        $extensionMatcher = '/.*' . preg_quote($fileExtension) . '$/';
26
27 2
        $blacklist = $this->prepareBlacklistPatterns($blacklist);
28
29
        /* @var $file \SplFileInfo */
30 2
        foreach ($files as $file) {
31 2
            if ($blacklist && preg_match('{('.implode('|', $blacklist).')}', $file->getPathname())) {
32 1
                continue;
33
            }
34
35 2
            if (!preg_match($extensionMatcher, $file->getBasename())) {
36 2
                continue;
37
            }
38
39 2
            yield $file->getPathname();
40
        }
41 2
    }
42
43 2
    private function prepareBlacklistPatterns(?array $blacklistPaths)
44
    {
45 2
        if ($blacklistPaths === null) {
46 2
            return $blacklistPaths;
47
        }
48
49 1
        foreach ($blacklistPaths as &$path) {
50 1
            $path = preg_replace('{/+}', '/', preg_quote(trim(strtr($path, '\\', '/'), '/')));
51 1
            $path = str_replace('\\*\\*', '.+?', $path);
52 1
            $path = str_replace('\\*', '[^/]+?', $path);
53
        }
54
55 1
        return $blacklistPaths;
56
    }
57
}
58