Skip to content

Support @readonly PHPDoc on the class as alternative to @immutable #3523

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
}
Loading