From ec5ce0aeaedbccd9865c7fb2503e6c91488d3054 Mon Sep 17 00:00:00 2001 From: David Scandurra Date: Sat, 30 Aug 2025 15:05:08 +0200 Subject: [PATCH] Fix setting known offset --- src/Analyser/MutatingScope.php | 7 +++++++ .../data/offset-access-value-assignment.php | 17 +++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/Analyser/MutatingScope.php b/src/Analyser/MutatingScope.php index 57d047fbf8..3a2d364900 100644 --- a/src/Analyser/MutatingScope.php +++ b/src/Analyser/MutatingScope.php @@ -750,6 +750,13 @@ public function getType(Expr $node): Type return $this->getType($node->getVar())->unsetOffset($this->getType($node->getDim())); } if ($node instanceof SetOffsetValueTypeExpr) { + $var = $node->getVar() instanceof OriginalPropertyTypeExpr ? $node->getVar()->getPropertyFetch() : $node->getVar(); + if ($node->getDim() !== null && $this->hasExpressionType(new Expr\ArrayDimFetch($var, $node->getDim()))->yes()) { + return $this->getType($node->getVar())->setExistingOffsetValueType( + $this->getType($node->getDim()), + $this->getType($node->getValue()), + ); + } return $this->getType($node->getVar())->setOffsetValueType( $node->getDim() !== null ? $this->getType($node->getDim()) : null, $this->getType($node->getValue()), diff --git a/tests/PHPStan/Rules/Arrays/data/offset-access-value-assignment.php b/tests/PHPStan/Rules/Arrays/data/offset-access-value-assignment.php index 2e4f00d7e3..bac11303d3 100644 --- a/tests/PHPStan/Rules/Arrays/data/offset-access-value-assignment.php +++ b/tests/PHPStan/Rules/Arrays/data/offset-access-value-assignment.php @@ -59,3 +59,20 @@ public function foo(): void $this->collection2[] = 2; } } + +class TestList +{ + + /** + * @var list + */ + public array $list = []; + + public function setKnownOffset(int $offset): void + { + if (isset($this->list[$offset])) { + $this->list[$offset] = 123; + } + } + +}