|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace ComposerRequireChecker\FileLocator; |
|
4
|
|
|
|
|
5
|
|
|
use Traversable; |
|
6
|
|
|
|
|
7
|
|
|
final class LocateAllFilesByExtension |
|
8
|
|
|
{ |
|
9
|
16 |
|
public function __invoke(Traversable $directories, string $fileExtension, ?array $blacklist): Traversable |
|
10
|
|
|
{ |
|
11
|
16 |
|
foreach ($directories as $directory) { |
|
12
|
15 |
|
yield from $this->filterFilesByExtension( |
|
13
|
15 |
|
new \RecursiveIteratorIterator( |
|
14
|
15 |
|
new \RecursiveDirectoryIterator($directory), |
|
15
|
15 |
|
\RecursiveIteratorIterator::LEAVES_ONLY |
|
16
|
|
|
), |
|
17
|
15 |
|
$fileExtension, |
|
18
|
15 |
|
$blacklist |
|
19
|
|
|
); |
|
20
|
|
|
} |
|
21
|
16 |
|
} |
|
22
|
|
|
|
|
23
|
15 |
|
private function filterFilesByExtension(Traversable $files, string $fileExtension, ?array $blacklist): Traversable |
|
24
|
|
|
{ |
|
25
|
15 |
|
$extensionMatcher = '/.*' . preg_quote($fileExtension) . '$/'; |
|
26
|
|
|
|
|
27
|
15 |
|
$blacklistMatcher = '{('.implode('|', $this->prepareBlacklistPatterns($blacklist)).')}'; |
|
28
|
|
|
|
|
29
|
|
|
/* @var $file \SplFileInfo */ |
|
30
|
15 |
|
foreach ($files as $file) { |
|
31
|
15 |
|
if ($blacklist && preg_match($blacklistMatcher, $file->getPathname())) { |
|
|
|
|
|
|
32
|
5 |
|
continue; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
15 |
|
if (!preg_match($extensionMatcher, $file->getBasename())) { |
|
36
|
15 |
|
continue; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
14 |
|
yield $file->getPathname(); |
|
40
|
|
|
} |
|
41
|
15 |
|
} |
|
42
|
|
|
|
|
43
|
15 |
|
private function prepareBlacklistPatterns(?array $blacklistPaths): array |
|
44
|
|
|
{ |
|
45
|
15 |
|
if ($blacklistPaths === null) { |
|
|
|
|
|
|
46
|
9 |
|
return []; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
10 |
|
$dirSep = \preg_quote(DIRECTORY_SEPARATOR, '{}'); |
|
50
|
|
|
|
|
51
|
10 |
|
foreach ($blacklistPaths as &$path) { |
|
52
|
9 |
|
$path = preg_replace('{' . $dirSep . '+}', DIRECTORY_SEPARATOR, \preg_quote(trim(str_replace('/', DIRECTORY_SEPARATOR, $path), DIRECTORY_SEPARATOR), '{}')); |
|
53
|
9 |
|
$path = str_replace('\\*\\*', '.+?', $path); |
|
54
|
9 |
|
$path = str_replace('\\*', '[^' . $dirSep . ']+?', $path); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
10 |
|
return $blacklistPaths; |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)or! empty(...)instead.