Skip to content

Commit 328fcb9

Browse files
committed
TypeSpecifier - understand preg_match() === 1 same way as preg_match()
1 parent 71f4223 commit 328fcb9

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

src/Analyser/TypeSpecifier.php

+16
Original file line numberDiff line numberDiff line change
@@ -1989,6 +1989,22 @@ public function resolveIdentical(Expr\BinaryOp\Identical $expr, Scope $scope, Ty
19891989
$unwrappedRightExpr = $rightExpr->getExpr();
19901990
}
19911991
$rightType = $scope->getType($rightExpr);
1992+
1993+
if (
1994+
$context->true()
1995+
&& $unwrappedLeftExpr instanceof FuncCall
1996+
&& $unwrappedLeftExpr->name instanceof Name
1997+
&& $unwrappedLeftExpr->name->toLowerString() === 'preg_match'
1998+
&& (new ConstantIntegerType(1))->isSuperTypeOf($rightType)->yes()
1999+
) {
2000+
return $this->specifyTypesInCondition(
2001+
$scope,
2002+
$leftExpr,
2003+
$context,
2004+
$rootExpr,
2005+
);
2006+
}
2007+
19922008
if (
19932009
$context->true()
19942010
&& $unwrappedLeftExpr instanceof FuncCall

tests/PHPStan/Analyser/nsrt/preg_match_shapes_php74.php

+31
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,34 @@ function testHoaUnsupportedRegexSyntax(string $s): void {
164164
}
165165
assertType('array{}|array{string}', $matches);
166166
}
167+
168+
function testPregMatchSimpleCondition(string $value): void {
169+
if (preg_match('/%env\((.*)\:.*\)%/U', $value, $matches)) {
170+
assertType('array{string, string}', $matches);
171+
}
172+
}
173+
174+
175+
function testPregMatchIdenticalToOne(string $value): void {
176+
if (preg_match('/%env\((.*)\:.*\)%/U', $value, $matches) === 1) {
177+
assertType('array{string, string}', $matches);
178+
}
179+
}
180+
181+
function testPregMatchIdenticalToOneFalseyContext(string $value): void {
182+
if (!(preg_match('/%env\((.*)\:.*\)%/U', $value, $matches) !== 1)) {
183+
assertType('array{string, string}', $matches);
184+
}
185+
}
186+
187+
function testPregMatchIdenticalToOneInverted(string $value): void {
188+
if (1 === preg_match('/%env\((.*)\:.*\)%/U', $value, $matches)) {
189+
assertType('array{string, string}', $matches);
190+
}
191+
}
192+
193+
function testPregMatchIdenticalToOneFalseyContextInverted(string $value): void {
194+
if (!(1 !== preg_match('/%env\((.*)\:.*\)%/U', $value, $matches))) {
195+
assertType('array{string, string}', $matches);
196+
}
197+
}

0 commit comments

Comments
 (0)