Skip to content

Commit fb031fa

Browse files
committed
Implementing FileMatcher
1 parent c5775d0 commit fb031fa

File tree

1 file changed

+76
-8
lines changed

1 file changed

+76
-8
lines changed

src/Util/FileMatcher.php

Lines changed: 76 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,8 @@
99
*/
1010
namespace PHPUnit\Util;
1111

12+
use InvalidArgumentException;
1213
use RuntimeException;
13-
use const DIRECTORY_SEPARATOR;
14-
use function basename;
15-
use function dirname;
16-
use function is_dir;
17-
use function mkdir;
18-
use function realpath;
19-
use function str_starts_with;
2014

2115
/**
2216
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for PHPUnit
@@ -26,14 +20,88 @@
2620
final readonly class FileMatcher
2721
{
2822
public static function match(string $path, FileMatcherPattern $pattern): bool
23+
{
24+
self::assertIsAbsolute($path);
25+
26+
$regex = self::toRegEx($pattern->path);
27+
dump($pattern->path, $regex, $path);
28+
29+
return preg_match($regex, $path) !== 0;
30+
}
31+
32+
/**
33+
* Based on webmozart/glob
34+
*
35+
* @return string The regular expression for matching the glob.
36+
*/
37+
public static function toRegEx($glob, $flags = 0): string
38+
{
39+
self::assertIsAbsolute($glob);
40+
41+
$inSquare = false;
42+
$regex = '';
43+
$length = strlen($glob);
44+
45+
for ($i = 0; $i < $length; ++$i) {
46+
$c = $glob[$i];
47+
48+
switch ($c) {
49+
case '?':
50+
$regex .= '.';
51+
break;
52+
53+
// the PHPUnit file iterator will match all
54+
// files within a wildcard, not just until the
55+
// next directory separator
56+
case '*':
57+
// if this is a ** but it is NOT preceded with `/` then
58+
// it is not a globstar and just interpret it as a literal
59+
if (($glob[$i + 1] ?? null) === '*') {
60+
$regex .= '\*\*';
61+
$i++;
62+
break;
63+
}
64+
$regex .= '.*';
65+
break;
66+
case '/':
67+
if (isset($glob[$i + 3]) && '**/' === $glob[$i + 1].$glob[$i + 2].$glob[$i + 3]) {
68+
$regex .= '/([^/]+/)*';
69+
$i += 3;
70+
break;
71+
}
72+
if ((!isset($glob[$i + 3])) && isset($glob[$i + 2]) && '**' === $glob[$i + 1].$glob[$i + 2]) {
73+
$regex .= '.*';
74+
$i += 2;
75+
break;
76+
}
77+
$regex .= '/';
78+
break;
79+
default:
80+
$regex .= $c;
81+
break;
82+
}
83+
}
84+
85+
if ($inSquare) {
86+
throw new InvalidArgumentException(sprintf(
87+
'Invalid glob: missing ] in %s',
88+
$glob
89+
));
90+
}
91+
92+
$regex .= '(/|$)';
93+
94+
return '{^'.$regex.'}';
95+
}
96+
97+
private static function assertIsAbsolute(string $path): void
2998
{
3099
if (substr($path, 0, 1) !== '/') {
31100
throw new RuntimeException(sprintf(
32101
'Path "%s" must be absolute',
33102
$path
34103
));
35104
}
36-
return false;
37105
}
38106
}
39107

0 commit comments

Comments
 (0)