Skip to content

Commit

Permalink
fix checks for phpstan/phpstan#8929
Browse files Browse the repository at this point in the history
of course just checking for ArrayAccess isn't enough - it's only valid
for index assignment operations 🤦
  • Loading branch information
pilif committed Jan 28, 2025
1 parent 99380da commit 8b59053
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
8 changes: 7 additions & 1 deletion src/Rules/Properties/ReadOnlyPropertyAssignRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use ArrayAccess;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Node\Expr\SetOffsetValueTypeExpr;
use PHPStan\Node\Expr\UnsetOffsetExpr;
use PHPStan\Node\PropertyAssignNode;
use PHPStan\Reflection\ConstructorsHelper;
use PHPStan\Reflection\MethodReflection;
Expand Down Expand Up @@ -91,7 +93,11 @@ public function processNode(Node $node, Scope $scope): array
continue;
}

if ((new ObjectType(ArrayAccess::class))->isSuperTypeOf($propertyReflection->getNativeType())->yes()) {
$expr = $node->getAssignedExpr();
if (
(new ObjectType(ArrayAccess::class))->isSuperTypeOf($propertyReflection->getNativeType())->yes()
&& (($expr instanceof SetOffsetValueTypeExpr) || ($expr instanceof UnsetOffsetExpr))
) {
continue;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,12 @@ public function testBug8929(): void
self::markTestSkipped('Test requires PHP 8.1');
}

$this->analyse([__DIR__ . '/data/bug-8929.php'], []);
$this->analyse([__DIR__ . '/data/bug-8929.php'], [
[
'Readonly property Bug8929\Test::$cache is assigned outside of the constructor.',
19,
],
]);
}

}
4 changes: 3 additions & 1 deletion tests/PHPStan/Rules/Properties/data/bug-8929.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ public function __construct()

public function add(object $key, mixed $value): void
{
$this->cache[$key] = $value;
$this->cache[$key] = $value; // valid offset access
unset($this->cache[$key]); // valid offset access
$this->cache = new \WeakMap(); // reassigning is invalid however
}
}

0 comments on commit 8b59053

Please sign in to comment.