Skip to content

Commit

Permalink
Retain list type when assigning to offset 1 of non-empty-list
Browse files Browse the repository at this point in the history
  • Loading branch information
herndlm committed Nov 27, 2024
1 parent 970117e commit 5570289
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/Type/IntersectionType.php
Original file line number Diff line number Diff line change
Expand Up @@ -756,7 +756,14 @@ public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $uni
);
});
}
return $this->intersectTypes(static fn (Type $type): Type => $type->setOffsetValueType($offsetType, $valueType, $unionValues));

$result = $this->intersectTypes(static fn (Type $type): Type => $type->setOffsetValueType($offsetType, $valueType, $unionValues));

if ($offsetType !== null && $this->isList()->yes() && $this->isIterableAtLeastOnce()->yes() && (new ConstantIntegerType(1))->isSuperTypeOf($offsetType)->yes()) {
$result = TypeCombinator::intersect($result, new AccessoryArrayListType());
}

return $result;
}

public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -692,4 +692,10 @@ public function testBug11617(): void
]);
}

public function testBug12131(): void
{
$this->checkExplicitMixed = true;
$this->analyse([__DIR__ . '/data/bug-12131.php'], []);
}

}
29 changes: 29 additions & 0 deletions tests/PHPStan/Rules/Properties/data/bug-12131.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php declare(strict_types = 1); // lint >= 7.4

namespace Bug12131;

class Test
{
/**
* @var non-empty-list<int>
*/
public array $array;

public function __construct()
{
$this->array = array_fill(0, 10, 1);
}

public function setAtZero(): void
{
$this->array[0] = 1;
}

public function setAtOne(): void
{
$this->array[1] = 1;
}
}

$a = new Test();
$a->setAtOne();

0 comments on commit 5570289

Please sign in to comment.