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