Skip to content

Commit 77527df

Browse files
ondrejmirtesclaude
andcommitted
Narrow falsey isset() on an optional constant-array offset
!isset($a['k']) where 'k' is an optional key with a non-nullable value type implies the key is absent, so remove HasOffsetType('k') from the subject - the counterpart of the removal already done for keys that surely exist, and of the falsey array_key_exists() narrowing. The removal is skipped when any union member can hold null at the offset (there the key may exist with a null value). With the falsey branch actually narrowed, branch merges see differing types for the subject and the conditional-expression guard machinery picks it up, so variables assigned under if (isset($a['k'])) regain their certainty when the same isset() is re-checked later. The `??=` value scope (which already applied this helper) now unsets the target offset, and a sealed all-optional shape intersected with non-empty-array collapses to its only possible key - the updated bug-15021 and isset-constant-array expectations record both, each strictly more precise than before. Closes phpstan/phpstan#9426 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CGhnJQpUWRRpg6H5LuWJkA
1 parent e606ca2 commit 77527df

7 files changed

Lines changed: 116 additions & 9 deletions

File tree

‎src/Analyser/ExprHandler/Helper/DefaultNarrowingHelper.php‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -687,13 +687,31 @@ public function createIssetSingleSubjectNonTrueTypes(
687687
if ($dimType instanceof ConstantIntegerType || $dimType instanceof ConstantStringType) {
688688
$constantArrays = $varType->getConstantArrays();
689689
$typesToRemove = [];
690+
$hasOptionalNonNullableOffset = false;
691+
$hasPossiblyNullOffsetValue = false;
690692
foreach ($constantArrays as $constantArray) {
691693
$hasOffset = $constantArray->hasOffsetValueType($dimType);
692-
if (!$hasOffset->yes() || !$constantArray->getOffsetValueType($dimType)->isNull()->no()) {
694+
if ($hasOffset->no()) {
693695
continue;
694696
}
697+
if (!$constantArray->getOffsetValueType($dimType)->isNull()->no()) {
698+
$hasPossiblyNullOffsetValue = true;
699+
continue;
700+
}
701+
702+
if ($hasOffset->yes()) {
703+
$typesToRemove[] = $constantArray;
704+
continue;
705+
}
706+
707+
$hasOptionalNonNullableOffset = true;
708+
}
695709

696-
$typesToRemove[] = $constantArray;
710+
// !isset() on an optional key with a non-nullable value means the
711+
// key is absent - but only when no member can hold null at that
712+
// offset (the removal distributes over every union member).
713+
if ($hasOptionalNonNullableOffset && !$hasPossiblyNullOffsetValue) {
714+
$typesToRemove[] = new HasOffsetType($dimType);
697715
}
698716

699717
if ($typesToRemove !== []) {

‎tests/PHPStan/Analyser/nsrt/bug-15021.php‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
/** @param array{foo?: string, bar?: string} $data */
88
function optionalOffset(array $data): void
99
{
10-
$data['foo'] ??= assertType('array{foo?: string, bar?: string}', $data);
10+
$data['foo'] ??= assertType('array{bar?: string}', $data);
1111
}
1212

1313
/** @param array{foo?: string, bar?: string} $data */
@@ -65,7 +65,7 @@ function nonNullableStaticProperty(): void
6565

6666
function propertyOffset(Foo $foo): void
6767
{
68-
$foo->data['foo'] ??= assertType('array{foo?: string, bar?: string}', $foo->data);
68+
$foo->data['foo'] ??= assertType('array{bar?: string}', $foo->data);
6969
}
7070

7171
/** @param \ArrayAccess<string, string> $a */
@@ -133,22 +133,22 @@ function unsetTargetBeforeAssignOp(array $data): void
133133
function emptyTargetBeforeAssignOp(array $data): void
134134
{
135135
if (empty($data['foo'])) {
136-
$data['foo'] ??= assertType('array{foo?: string, bar?: string}', $data);
136+
$data['foo'] ??= assertType('array{bar?: string}', $data);
137137
}
138138
}
139139

140140
/** @param array{foo?: string, bar?: string} $data */
141141
function assignOpInsideEmpty(array $data): void
142142
{
143-
if (empty($data['foo'] ??= assertType('array{foo?: string, bar?: string}', $data))) {
143+
if (empty($data['foo'] ??= assertType('array{bar?: string}', $data))) {
144144
echo 'empty';
145145
}
146146
}
147147

148148
/** @param array{foo?: string, bar?: string} $data */
149149
function assignOpInsideIsset(array $data): void
150150
{
151-
if (isset($data['foo'] ??= assertType('array{foo?: string, bar?: string}', $data))) {
151+
if (isset($data['foo'] ??= assertType('array{bar?: string}', $data))) {
152152
echo 'isset';
153153
}
154154
}
@@ -157,7 +157,7 @@ function assignOpInsideIsset(array $data): void
157157
function assignOpInsideUnsetOffset(array $data): void
158158
{
159159
$other = ['x' => 1, 'fallback' => 2];
160-
unset($other[$data['foo'] ??= assertType('array{foo?: string, bar?: string}', $data)]);
160+
unset($other[$data['foo'] ??= assertType('array{bar?: string}', $data)]);
161161
}
162162

163163
/** @param array{foo?: string, bar?: string} $data */
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
3+
namespace Bug9426;
4+
5+
use PHPStan\TrinaryLogic;
6+
use function PHPStan\Testing\assertType;
7+
use function PHPStan\Testing\assertVariableCertainty;
8+
9+
final class A
10+
{
11+
12+
/**
13+
* @param array{something?: string} $a
14+
*/
15+
public function something(array $a): void
16+
{
17+
if (isset($a['something'])) {
18+
$b = new \DateTimeImmutable();
19+
}
20+
21+
if (!isset($a['something'])) {
22+
assertType('array{}', $a);
23+
assertVariableCertainty(TrinaryLogic::createNo(), $b);
24+
} else {
25+
assertType('array{something: string}', $a);
26+
assertVariableCertainty(TrinaryLogic::createYes(), $b);
27+
}
28+
}
29+
30+
/**
31+
* @param array{something?: string|null} $a
32+
*/
33+
public function nullableValueStaysUntouched(array $a): void
34+
{
35+
if (!isset($a['something'])) {
36+
assertType('array{something?: string|null}', $a);
37+
} else {
38+
assertType('array{something: string}', $a);
39+
}
40+
}
41+
42+
}

‎tests/PHPStan/Rules/Variables/DefinedVariableRuleTest.php‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1094,6 +1094,15 @@ public function testBug10228(): void
10941094
$this->analyse([__DIR__ . '/data/bug-10228.php'], []);
10951095
}
10961096

1097+
public function testBug9426(): void
1098+
{
1099+
$this->cliArgumentsVariablesRegistered = true;
1100+
$this->polluteScopeWithLoopInitialAssignments = true;
1101+
$this->checkMaybeUndefinedVariables = true;
1102+
$this->polluteScopeWithAlwaysIterableForeach = true;
1103+
$this->analyse([__DIR__ . '/data/bug-9426.php'], []);
1104+
}
1105+
10971106
#[RequiresPhp('>= 8.4.0')]
10981107
public function testPropertyHooks(): void
10991108
{

‎tests/PHPStan/Rules/Variables/IssetRuleTest.php‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -567,9 +567,13 @@ public function testIssetConstantArray(): void
567567
13,
568568
],
569569
[
570-
'Offset 3 on array{string, string, string, string, string} in isset() always exists and is not nullable.',
570+
'Offset 3 on array{0: string, 1: string, 2: string, 4: string} in isset() does not exist.',
571571
17,
572572
],
573+
[
574+
'Offset 3 on array{string, string, string, string, string} in isset() always exists and is not nullable.',
575+
29,
576+
],
573577
]);
574578
}
575579

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Bug9426Rule;
6+
7+
final class A
8+
{
9+
/**
10+
* @param array{something?: string} $a
11+
*/
12+
public function something(array $a): void
13+
{
14+
if (isset($a['something'])) {
15+
$b = new \DateTimeImmutable();
16+
}
17+
18+
$c = [
19+
!isset($a['something']) ? 'something' : $b,
20+
];
21+
}
22+
}

‎tests/PHPStan/Rules/Variables/data/isset-constant-array.php‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,18 @@ public function sayHello(array $list): bool
1313
return isset($list[2]); // offset 3 implies offset 2;
1414
}
1515

16+
if (isset($list[4])) {
17+
return isset($list[3]); // offset 4 cannot be set - offset 3 is not (see above), and the list is contiguous
18+
}
19+
20+
return false;
21+
}
22+
23+
/**
24+
* @param list{0: string, 1: string, 2?: string, 3?: string, 4?: string} $list
25+
*/
26+
public function sayGoodbye(array $list): bool
27+
{
1628
if (isset($list[4])) {
1729
return isset($list[3]); // offset 4 implies offset 3;
1830
}

0 commit comments

Comments
 (0)