From 61a968e36f73192118cf89199eed2ecc00e88e4d Mon Sep 17 00:00:00 2001 From: VincentLanglet <9052536+VincentLanglet@users.noreply.github.com> Date: Sat, 16 May 2026 12:28:30 +0000 Subject: [PATCH] Skip non-discriminating guards in `createConditionalExpressions` even when target is not tracked in the other scope - In `MutatingScope::createConditionalExpressions`, the filter that skips non-discriminating guards previously required the target expression to exist in the other scope's expression types. When the target was absent (e.g. `$options['multiple']` not explicitly narrowed in the truthy branch), the filter did not fire, allowing guards like `$instructions` (an unrelated mutable variable) to create spurious conditional expression holders. - Add an additional check: if the guard variable's type in our scope is definitively a supertype of its type in the other scope (`.yes()`), the guard is non-discriminating regardless of the target's presence, so skip it. - The original check (requiring both target and guard in the other scope, using `!.no()`) is preserved for cases where the target IS tracked, to avoid regressions with `maybe` supertype results (e.g. `Event` vs `OrderInterface`). - Also fixes the same bug with strict comparison (`!==` instead of `!=`). --- src/Analyser/MutatingScope.php | 13 +++++-- tests/PHPStan/Analyser/nsrt/bug-14595.php | 45 +++++++++++++++++++++++ 2 files changed, 54 insertions(+), 4 deletions(-) create mode 100644 tests/PHPStan/Analyser/nsrt/bug-14595.php diff --git a/src/Analyser/MutatingScope.php b/src/Analyser/MutatingScope.php index daf5bb9eb3..213ed039a1 100644 --- a/src/Analyser/MutatingScope.php +++ b/src/Analyser/MutatingScope.php @@ -3749,11 +3749,16 @@ private function createConditionalExpressions( foreach ($variableTypeGuards as $guardExprString => $guardHolder) { if ( - array_key_exists($exprString, $theirExpressionTypes) - && $theirExpressionTypes[$exprString]->getCertainty()->yes() - && array_key_exists($guardExprString, $theirExpressionTypes) + array_key_exists($guardExprString, $theirExpressionTypes) && $theirExpressionTypes[$guardExprString]->getCertainty()->yes() - && !$guardHolder->getType()->isSuperTypeOf($theirExpressionTypes[$guardExprString]->getType())->no() + && ( + ( + array_key_exists($exprString, $theirExpressionTypes) + && $theirExpressionTypes[$exprString]->getCertainty()->yes() + && !$guardHolder->getType()->isSuperTypeOf($theirExpressionTypes[$guardExprString]->getType())->no() + ) + || $guardHolder->getType()->isSuperTypeOf($theirExpressionTypes[$guardExprString]->getType())->yes() + ) ) { continue; } diff --git a/tests/PHPStan/Analyser/nsrt/bug-14595.php b/tests/PHPStan/Analyser/nsrt/bug-14595.php new file mode 100644 index 0000000000..cee7eee39f --- /dev/null +++ b/tests/PHPStan/Analyser/nsrt/bug-14595.php @@ -0,0 +1,45 @@ +