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
27 changes: 26 additions & 1 deletion src/Analyser/MutatingScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -3216,9 +3216,34 @@ public function filterBySpecifiedTypes(SpecifiedTypes $specifiedTypes): self
if (array_key_exists($conditionalExprString, $conditions)) {
continue;
}

// Pass 1: Prefer exact matches
foreach ($conditionalExpressions as $conditionalExpression) {
foreach ($conditionalExpression->getConditionExpressionTypeHolders() as $holderExprString => $conditionalTypeHolder) {
if (
!array_key_exists($holderExprString, $specifiedExpressions)
|| !$conditionalTypeHolder->equals($specifiedExpressions[$holderExprString])
) {
continue 2;
}
}

$conditions[$conditionalExprString][] = $conditionalExpression;
$specifiedExpressions[$conditionalExprString] = $conditionalExpression->getTypeHolder();
}

if (array_key_exists($conditionalExprString, $conditions)) {
continue;
}

// Pass 2: Supertype match. Only runs when Pass 1 found no exact match for this expression.
foreach ($conditionalExpressions as $conditionalExpression) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my understanding of this change is:

in the first loop (line 3221) we do a speed optimized check with

						if (
							!array_key_exists($holderExprString, $specifiedExpressions)
							|| !$conditionalTypeHolder->equals($specifiedExpressions[$holderExprString])
						) {
							continue 2;
						}

which does not work good for e.g. MixedType (because its not equal, but just a super-type of everything).
therefore we need the second loop (line 3239) to process only those expressions/types again, which did not match the fast equal-type check, but might still be useful because of "real isSuperTypeOf" typing logic...?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reviewer's understanding is correct. I've added detailed comments explaining the two-pass condition matching approach:

  • Pass 1 uses exact equals() matching — this is the fast path that handles most cases and takes priority.
  • Pass 2 uses isSuperTypeOf() matching — this only runs when Pass 1 found no match. It handles cases where the condition type is broader than the narrowed expression type (e.g., a union condition 'value1'|'value2' matching a narrowed 'value1', or int|string from scope merging matching a narrowed int).
  • Why Pass 1 must take priority: When both exact and broader conditions exist (from scope merging creating both specific and general conditions), using isSuperTypeOf for both would cause the broader match to degrade certainty via extremeIdentity (Yes AND Maybe = Maybe), leading to false "variable might not be defined" warnings.

All tests pass (11852 tests, 79360 assertions) and make phpstan reports no errors.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

my understanding of this change is:

in the first loop (line 3221) we do a speed optimized check with

						if (
							!array_key_exists($holderExprString, $specifiedExpressions)
							|| !$conditionalTypeHolder->equals($specifiedExpressions[$holderExprString])
						) {
							continue 2;
						}

which does not work good for e.g. MixedType (because its not equal, but just a super-type of everything). therefore we need the second loop (line 3239) to process only those expressions/types again, which did not match the fast equal-type check, but might still be useful because of "real isSuperTypeOf" typing logic...?

The idea is that you might have conditionalExpression which has matching exactly and we prefer this one other the one which only match with isSuperTypeOf.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pushed. The comment was updated to clarify VincentLanglet's point: the two-pass approach exists to prefer exact matches over supertype matches (not just for speed). The explanation of why this preference matters (certainty degradation via extremeIdentity) was moved from Pass 2's comment block to Pass 1's, where the preference is actually enforced.

foreach ($conditionalExpression->getConditionExpressionTypeHolders() as $holderExprString => $conditionalTypeHolder) {
if (!array_key_exists($holderExprString, $specifiedExpressions) || !$specifiedExpressions[$holderExprString]->equals($conditionalTypeHolder)) {
if (
!array_key_exists($holderExprString, $specifiedExpressions)
|| !$conditionalTypeHolder->getCertainty()->equals($specifiedExpressions[$holderExprString]->getCertainty())
|| !$conditionalTypeHolder->getType()->isSuperTypeOf($specifiedExpressions[$holderExprString]->getType())->yes()
) {
continue 2;
}
}
Expand Down
32 changes: 32 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-10055.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php // lint >= 8.0

declare(strict_types = 1);

namespace Bug10055;

use function PHPStan\Testing\assertType;

/**
* @param 'value1'|'value2'|'value3' $param1
* @param ($param1 is 'value3' ? bool : int) $param2
*/
function test(string $param1, int|bool $param2): void
{
match ($param1) {
'value1' => assertType('int', $param2),
'value2' => assertType('int', $param2),
'value3' => assertType('bool', $param2),
};
}

function testScopeMerging(mixed $foo): void
{
$a = 0;
if (\is_string($foo) || \is_int($foo)) {
$a = 1;
}

if (\is_int($foo)) {
assertType('1', $a);
}
}
28 changes: 28 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-10422.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types = 1);

namespace Bug10422;

use function PHPStan\Testing\assertType;

class TestClass {
public function test(): void {}
public function something(): bool { return true; }
}

function test(?TestClass $test): void
{
$error = '';

if (!$test) {
$error = 'missing test';
} else if ($test->something()) {
$error = 'another';
}
if ($error) {
die('Done');
}
assertType('Bug10422\TestClass', $test);
$test->test();
}
24 changes: 24 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-13591.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types = 1);

namespace Bug13591;

use function PHPStan\Testing\assertType;

function processHotel(int $hotelId): void {}

/**
* @param 'get_rooms'|'get_hotels' $action
*/
function test(string $action, ?int $hotelId): void
{
if ($action === 'get_rooms' && $hotelId === null) {
throw new \InvalidArgumentException('Hotel ID is required');
}

if ($action === 'get_rooms') {
assertType('int', $hotelId);
processHotel($hotelId);
}
}
46 changes: 46 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-4090.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types = 1);

namespace Bug4090;

use function PHPStan\Testing\assertType;

/** @param string[] $a */
function foo(array $a): void
{
if (count($a) > 1) {
echo implode(',', $a);
} elseif (count($a) === 1) {
assertType('string', current($a));
echo trim(current($a));
}
}

/** @param string[] $a */
function bar(array $a): void
{
$count = count($a);
if ($count > 1) {
echo implode(',', $a);
} elseif ($count === 1) {
assertType('string', current($a));
echo trim(current($a));
}
}

/** @param string[] $a */
function qux(array $a): void
{
switch (count($a)) {
case 0:
break;
case 1:
assertType('string', current($a));
echo trim(current($a));
break;
default:
echo implode(',', $a);
break;
}
}
14 changes: 7 additions & 7 deletions tests/PHPStan/Analyser/nsrt/bug-5051.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,35 +60,35 @@ public function testWithBooleans($data): void
assertType('bool', $update);
} else {
assertType('1|2', $data);
assertType('bool', $update);
assertType('false', $update);
}

if ($data === 1) {
assertType('bool', $update);
assertType('bool', $foo);
assertType('false', $update);
assertType('false', $foo);
} else {
assertType('bool', $update);
assertType('bool', $foo);
}

if ($data === 2) {
assertType('bool', $update);
assertType('bool', $foo);
assertType('false', $update);
assertType('false', $foo);
} else {
assertType('bool', $update);
assertType('bool', $foo);
}

if ($data === 3) {
assertType('bool', $update);
assertType('false', $update);
assertType('true', $foo);
} else {
assertType('bool', $update);
assertType('bool', $foo);
}

if ($data === 1 || $data === 2) {
assertType('bool', $update);
assertType('false', $update);
assertType('false', $foo);
} else {
assertType('bool', $update);
Expand Down
24 changes: 24 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-6663.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php // lint >= 8.0

declare(strict_types = 1);

namespace Bug6663;

use function PHPStan\Testing\assertType;

class X {}
class Y {}

function test(mixed $xy, mixed $ab): void
{
if ($xy instanceof X || $ab instanceof X) {
if ($xy instanceof Y) {
assertType('Bug6663\Y', $xy);
assertType('Bug6663\X', $ab);
}
if ($ab instanceof Y) {
assertType('Bug6663\X', $xy);
assertType('Bug6663\Y', $ab);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1277,4 +1277,11 @@ public function testBug14308(): void
$this->analyse([__DIR__ . '/data/bug-14308.php'], []);
}

public function testBug11218(): void
{
$this->reportPossiblyNonexistentConstantArrayOffset = true;

$this->analyse([__DIR__ . '/data/bug-11218.php'], []);
}

}
18 changes: 18 additions & 0 deletions tests/PHPStan/Rules/Arrays/data/bug-11218.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php declare(strict_types = 1);

namespace Bug11218Array;

function test(): void
{
$level = 'test';

$test = [];

for ($i = 0 ; $i <= 3 ; $i++) {
if ($i === 0) {
$test[$level] = 'this is a';
} else {
$test[$level] .= ' test';
}
}
}
10 changes: 10 additions & 0 deletions tests/PHPStan/Rules/Functions/CallToFunctionParametersRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2828,4 +2828,14 @@ public function testBug4608(): void
]);
}

public function testBug13591(): void
{
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-13591.php'], []);
}

public function testBug4090(): void
{
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-4090.php'], []);
}

}
8 changes: 8 additions & 0 deletions tests/PHPStan/Rules/Methods/CallMethodsRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4001,4 +4001,12 @@ public function testBug11978(): void
]);
}

public function testBug10422(): void
{
$this->checkThisOnly = false;
$this->checkNullables = true;
$this->checkUnionTypes = true;
$this->analyse([__DIR__ . '/../../Analyser/nsrt/bug-10422.php'], []);
}

}
18 changes: 18 additions & 0 deletions tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1499,4 +1499,22 @@ public function testBug14117(): void
]);
}

public function testBug12597(): void
{
$this->cliArgumentsVariablesRegistered = true;
$this->polluteScopeWithLoopInitialAssignments = false;
$this->checkMaybeUndefinedVariables = true;
$this->polluteScopeWithAlwaysIterableForeach = true;
$this->analyse([__DIR__ . '/data/bug-12597.php'], []);
}

public function testBug11218(): void
{
$this->cliArgumentsVariablesRegistered = true;
$this->polluteScopeWithLoopInitialAssignments = false;
$this->checkMaybeUndefinedVariables = true;
$this->polluteScopeWithAlwaysIterableForeach = true;
$this->analyse([__DIR__ . '/data/bug-11218.php'], []);
}

}
16 changes: 16 additions & 0 deletions tests/PHPStan/Rules/Variables/data/bug-11218.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php declare(strict_types = 1);

namespace Bug11218;

function test(): void
{
$level = 'test';

for ($i = 0 ; $i <= 3 ; $i++) {
if ($i === 0) {
$test[$level] = 'this is a';
} else {
$test[$level] .= ' test';
}
}
}
24 changes: 24 additions & 0 deletions tests/PHPStan/Rules/Variables/data/bug-12597.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

declare(strict_types = 1);

namespace Bug12597;

class HelloWorld
{
private const TYPE_1 = 1;
private const TYPE_2 = 2;

public function test(int $type): void
{
if (in_array($type, [self::TYPE_1, self::TYPE_2], true)) {
$message = 'Hello!';
}

if ($type === self::TYPE_1) {
$this->message($message);
}
}

public function message(string $message): void {}
}
Loading