Skip to content

Commit f5632ba

Browse files
committed
Unmatched optional group followed by a matched one is '' in preg_match_all() with PREG_SET_ORDER
Amp-Thread-ID: https://ampcode.com/threads/T-01a177b5-960f-71d2-a3e2-fa7649f39d2c
1 parent 5c257d7 commit f5632ba

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

‎src/Type/Php/RegexArrayShapeMatcher.php‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -407,7 +407,8 @@ private function createGroupValueType(RegexCapturingGroup $captureGroup, Trinary
407407
$this->containsSetOrder($flags)
408408
&& !$this->containsUnmatchedAsNull($flags, $matchesAll)
409409
&& $captureGroup->isOptional()
410-
&& !$isTrailingOptional
410+
// an unmatched group followed by a matched one is reported as ''
411+
&& !$isLastGroup
411412
)
412413
) {
413414
$groupValueType = $this->getValueType(

‎tests/PHPStan/Analyser/nsrt/preg_match_all_shapes.php‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,3 +198,20 @@ function bug11661(): void {
198198
assertType("list<array{0: string, 1?: 'ERR'}>", $results);
199199

200200
}
201+
202+
function setOrderOptionalGroupFollowedByMatchedGroup(string $s): void {
203+
// from php-src ext/pcre/tests/bug61780_1.phpt
204+
if (preg_match_all('/(4)?(2)?\d/', $s, $matches, PREG_SET_ORDER)) {
205+
assertType("non-empty-list<array{0: string, 1?: ''|'4', 2?: '2'}>", $matches);
206+
}
207+
208+
// from php-src ext/pcre/tests/bug61780_2.phpt
209+
if (preg_match_all('/(?<a>4)?(?<b>2)?\d/', $s, $matches, PREG_SET_ORDER)) {
210+
assertType("non-empty-list<array{0: string, a?: ''|'4', 1?: ''|'4', b?: '2', 2?: '2'}>", $matches);
211+
}
212+
213+
// from php-src ext/pcre/tests/preg_replace_callback_flags.phpt
214+
if (preg_match_all('/(a)|(b)/', $s, $matches, PREG_SET_ORDER)) {
215+
assertType("non-empty-list<array{0: string, 1?: ''|'a', 2?: 'b'}>", $matches);
216+
}
217+
}

0 commit comments

Comments
 (0)