From 951ab2073904076868b680adeefea34e02340614 Mon Sep 17 00:00:00 2001 From: Martin Herndl Date: Wed, 2 Oct 2024 14:42:17 +0200 Subject: [PATCH] Support `@readonly` PHPDoc on the class as alternative to `@immutable` --- src/Reflection/ClassReflection.php | 2 +- ...ReadOnlyByPhpDocPropertyAssignRuleTest.php | 14 ++++++ .../Rules/Properties/data/feature-11775.php | 45 +++++++++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 tests/PHPStan/Rules/Properties/data/feature-11775.php diff --git a/src/Reflection/ClassReflection.php b/src/Reflection/ClassReflection.php index d980be78649..ef56a360da7 100644 --- a/src/Reflection/ClassReflection.php +++ b/src/Reflection/ClassReflection.php @@ -1238,7 +1238,7 @@ public function isImmutable(): bool { if ($this->isImmutable === null) { $resolvedPhpDoc = $this->getResolvedPhpDoc(); - $this->isImmutable = $resolvedPhpDoc !== null && $resolvedPhpDoc->isImmutable(); + $this->isImmutable = $resolvedPhpDoc !== null && ($resolvedPhpDoc->isImmutable() || $resolvedPhpDoc->isReadOnly()); $parentClass = $this->getParentClass(); if ($parentClass !== null && !$this->isImmutable) { diff --git a/tests/PHPStan/Rules/Properties/ReadOnlyByPhpDocPropertyAssignRuleTest.php b/tests/PHPStan/Rules/Properties/ReadOnlyByPhpDocPropertyAssignRuleTest.php index e5496fc6463..9fde9f5eca2 100644 --- a/tests/PHPStan/Rules/Properties/ReadOnlyByPhpDocPropertyAssignRuleTest.php +++ b/tests/PHPStan/Rules/Properties/ReadOnlyByPhpDocPropertyAssignRuleTest.php @@ -160,4 +160,18 @@ public function testFeature7648(): void $this->analyse([__DIR__ . '/data/feature-7648.php'], []); } + public function testFeature11775(): void + { + $this->analyse([__DIR__ . '/data/feature-11775.php'], [ + [ + '@readonly property Feature11775\FooImmutable::$i is assigned outside of the constructor.', + 22, + ], + [ + '@readonly property Feature11775\FooReadonly::$i is assigned outside of the constructor.', + 43, + ], + ]); + } + } diff --git a/tests/PHPStan/Rules/Properties/data/feature-11775.php b/tests/PHPStan/Rules/Properties/data/feature-11775.php new file mode 100644 index 00000000000..c3dfe4fce24 --- /dev/null +++ b/tests/PHPStan/Rules/Properties/data/feature-11775.php @@ -0,0 +1,45 @@ +i = $i; + } + + public function getId(): int + { + return $this->i; + } + + public function setId(): void + { + $this->i = 5; + } +} + +/** @readonly */ +class FooReadonly +{ + private int $i; + + public function __construct(int $i) + { + $this->i = $i; + } + + public function getId(): int + { + return $this->i; + } + + public function setId(): void + { + $this->i = 5; + } +}