Skip to content

Commit

Permalink
Support @readonly PHPDoc on the class as alternative to @immutable
Browse files Browse the repository at this point in the history
  • Loading branch information
herndlm committed Oct 14, 2024
1 parent 6ac62d3 commit 8d193e4
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Reflection/ClassReflection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -160,4 +160,22 @@ public function testFeature7648(): void
$this->analyse([__DIR__ . '/data/feature-7648.php'], []);
}

public function testFeature11775(): void
{
if (PHP_VERSION_ID < 70400) {
$this->markTestSkipped('Test requires PHP 7.4.');
}

$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,
],
]);
}

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

namespace Feature11775;

/** @immutable */
class FooImmutable
{
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;
}
}

/** @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;
}
}

0 comments on commit 8d193e4

Please sign in to comment.