Skip to content

Commit

Permalink
RegexArrayShapeMatcher: Fix non-emptiness of leading optional groups
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm committed Jul 25, 2024
1 parent c4c0269 commit 05705ce
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/Type/Php/RegexArrayShapeMatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -286,12 +286,13 @@ private function buildArrayType(
$countGroups = count($captureGroups);
$i = 0;
foreach ($captureGroups as $captureGroup) {
$isTraillingOptional = $i >= $countGroups - $trailingOptionals;

Check warning on line 289 in src/Type/Php/RegexArrayShapeMatcher.php

View workflow job for this annotation

GitHub Actions / Check for typos

"Trailling" should be "Trailing" or "Trialling" or "Trilling".
$groupValueType = $this->getValueType($captureGroup->getType(), $flags);

if (!$wasMatched->yes()) {
$optional = true;
} else {
if ($i < $countGroups - $trailingOptionals) {
if (!$isTraillingOptional) {

Check warning on line 295 in src/Type/Php/RegexArrayShapeMatcher.php

View workflow job for this annotation

GitHub Actions / Check for typos

"Trailling" should be "Trailing" or "Trialling" or "Trilling".
$optional = false;
if ($this->containsUnmatchedAsNull($flags) && !$captureGroup->isOptional()) {
$groupValueType = TypeCombinator::removeNull($groupValueType);
Expand All @@ -303,7 +304,7 @@ private function buildArrayType(
}
}

if (!$optional && $captureGroup->isOptional() && !$this->containsUnmatchedAsNull($flags)) {
if (!$isTraillingOptional && $captureGroup->isOptional() && !$this->containsUnmatchedAsNull($flags)) {

Check warning on line 307 in src/Type/Php/RegexArrayShapeMatcher.php

View workflow job for this annotation

GitHub Actions / Check for typos

"Trailling" should be "Trailing" or "Trialling" or "Trilling".
$groupValueType = TypeCombinator::union($groupValueType, new ConstantStringType(''));
}

Expand Down
15 changes: 15 additions & 0 deletions tests/PHPStan/Analyser/nsrt/preg_match_shapes.php
Original file line number Diff line number Diff line change
Expand Up @@ -525,3 +525,18 @@ function (string $s): void {
assertType("array{0?: string, 1?: ''|numeric-string}", $matches);
};

class Bug11376
{
public function test(string $str): void
{
preg_match('~^(?:(\w+)::)?(\w+)$~', $str, $matches);
assertType('array{0?: string, 1?: string, 2?: non-empty-string}', $matches);
}

public function test2(string $str): void
{
if (preg_match('~^(?:(\w+)::)?(\w+)$~', $str, $matches) === 1) {
assertType('array{string, string, non-empty-string}', $matches);
}
}
}

0 comments on commit 05705ce

Please sign in to comment.