Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -201,10 +201,12 @@ public function processBooleanConditionalTypes(Scope $scope, SpecifiedTypes $con
}

$conditions = $conditionExpressionTypes;
$droppedSelfCondition = null;
foreach (array_keys($conditions) as $conditionExprString) {
if ($conditionExprString !== $exprString) {
continue;
}
$droppedSelfCondition = $conditions[$conditionExprString];
unset($conditions[$conditionExprString]);
}

Expand All @@ -218,6 +220,23 @@ public function processBooleanConditionalTypes(Scope $scope, SpecifiedTypes $con
? TypeCombinator::intersect($targetType, $type)
: TypeCombinator::remove($targetType, $type);

// A condition on the target expression itself cannot be tracked
// (the holder fires by matching *other* expressions) so it is
// dropped above. But that condition restricted the target to a
// subset of its values; without it the holder must also allow the
// values the condition excluded, otherwise it over-narrows the
// target when only the remaining conditions hold. Example:
// `!(isset($a['foo']) && !is_array($a['foo']))` keyed on
// `$a` having offset 'foo' must yield `array|null`, not `array`,
// because `$a['foo']` may be null when the dropped `isset` (i.e.
// non-null) condition does not hold.
if ($droppedSelfCondition !== null) {
$complement = TypeCombinator::remove($scope->getType($expr), $droppedSelfCondition->getType());
if (!$complement instanceof NeverType) {
$holderType = TypeCombinator::union($holderType, $complement);
}
}

// These boolean-decomposition holders only refine an expression's
// type in a future scope; they must never collapse it to never and
// thereby mark the whole scope unreachable. A never result is an
Expand Down
29 changes: 29 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-14874.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php declare(strict_types = 1);

namespace Bug14874;

use function PHPStan\Testing\assertType;

/**
* @param array<mixed> $a
*/
function test(array $a): bool {
if (isset($a['foo']) && !is_array($a['foo']))
return false;
if (array_key_exists('foo', $a)) {
assertType('array<mixed, mixed>|null', $a['foo']);
return $a['foo'] === null; // possible
}
return false;
}

/**
* @param array<mixed> $a
*/
function testIs(array $a): void {
if (isset($a['foo']) && !is_int($a['foo']))
return;
if (array_key_exists('foo', $a)) {
assertType('int|null', $a['foo']);
}
}
Loading