Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/Type/Regex/RegexGroupParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,30 @@ private function walkGroupAst(
}

if ($ast->getId() === '#alternation') {
$inAlternation = true;
$newLiterals = [];
foreach ($children as $child) {
$walkResult = $this->walkGroupAst(
$child,
true,
$inClass,
$patternModifiers,
$walkResult->onlyLiterals([]),
);

if ($newLiterals === null) {
continue;
}

if (count($walkResult->getOnlyLiterals() ?? []) > 0) {
foreach ($walkResult->getOnlyLiterals() as $alternationLiterals) {
$newLiterals[] = $alternationLiterals;
}
} else {
$newLiterals = null;
}
}

return $walkResult->onlyLiterals($newLiterals);
}

// [^0-9] should not parse as numeric-string, and [^list-everything-but-numbers] is technically
Expand Down
19 changes: 19 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-12173.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php // lint >= 7.4

namespace Bug12173;

use function PHPStan\Testing\assertType;

class HelloWorld
{
public function parse(string $string): void
{
$regex = '#.*(?<fruit>(apple|orange)).*#';

if (preg_match($regex, $string, $matches) !== 1) {
throw new \Exception('Invalid input');
}

assertType("'apple'|'orange'", $matches['fruit']);;
}
}
27 changes: 27 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-12210.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php // lint >= 7.4

declare(strict_types = 1);

namespace Bug12210;

use function PHPStan\Testing\assertType;

function bug12210a(string $text): void {
assert(preg_match('(((sum|min|max)))', $text, $match) === 1);
assertType("array{string, 'max'|'min'|'sum', 'max'|'min'|'sum'}", $match);
}

function bug12210b(string $text): void {
assert(preg_match('(((sum|min|ma.)))', $text, $match) === 1);
assertType("array{string, non-empty-string, non-falsy-string}", $match);
}

function bug12210c(string $text): void {
assert(preg_match('(((su.|min|max)))', $text, $match) === 1);
assertType("array{string, non-empty-string, non-falsy-string}", $match);
}

function bug12210d(string $text): void {
assert(preg_match('(((sum|mi.|max)))', $text, $match) === 1);
assertType("array{string, non-empty-string, non-falsy-string}", $match);
}
Loading