Skip to content

Commit

Permalink
TypeSpecifier - understand preg_match() == 1 same way as === 1
Browse files Browse the repository at this point in the history
  • Loading branch information
staabm authored and ondrejmirtes committed Jun 21, 2024
1 parent 721a0a6 commit d842380
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Analyser/TypeSpecifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -1901,6 +1901,16 @@ public function resolveEqual(Expr\BinaryOp\Equal $expr, Scope $scope, TypeSpecif
) {
return $this->specifyTypesInCondition($scope, new Expr\BinaryOp\Identical($expr->left, $expr->right), $context, $rootExpr);
}

if (
$context->true()
&& $exprNode instanceof FuncCall
&& $exprNode->name instanceof Name
&& $exprNode->name->toLowerString() === 'preg_match'
&& (new ConstantIntegerType(1))->isSuperTypeOf($constantType)->yes()
) {
return $this->specifyTypesInCondition($scope, new Expr\BinaryOp\Identical($expr->left, $expr->right), $context, $rootExpr);
}
}

$leftType = $scope->getType($expr->left);
Expand Down
24 changes: 24 additions & 0 deletions tests/PHPStan/Analyser/nsrt/preg_match_shapes_php74.php
Original file line number Diff line number Diff line change
Expand Up @@ -195,3 +195,27 @@ function testPregMatchIdenticalToOneFalseyContextInverted(string $value): void {
assertType('array{string, string}', $matches);
}
}

function testPregMatchEqualToOne(string $value): void {
if (preg_match('/%env\((.*)\:.*\)%/U', $value, $matches) == 1) {
assertType('array{string, string}', $matches);
}
}

function testPregMatchEqualToOneFalseyContext(string $value): void {
if (!(preg_match('/%env\((.*)\:.*\)%/U', $value, $matches) != 1)) {
assertType('array{string, string}', $matches);
}
}

function testPregMatchEqualToOneInverted(string $value): void {
if (1 == preg_match('/%env\((.*)\:.*\)%/U', $value, $matches)) {
assertType('array{string, string}', $matches);
}
}

function testPregMatchEqualToOneFalseyContextInverted(string $value): void {
if (!(1 != preg_match('/%env\((.*)\:.*\)%/U', $value, $matches))) {
assertType('array{string, string}', $matches);
}
}

0 comments on commit d842380

Please sign in to comment.