Skip to content
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
8 changes: 2 additions & 6 deletions src/Rule/EnforceReadonlyPublicPropertyRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,11 @@ public function processNode(Node $node, Scope $scope): array
return [];
}

if (!$node->isPublic() || $node->isReadOnly()) {
if (!$node->isPublic() || $node->isReadOnly() || $node->hasHooks()) {
return [];
}

$classReflection = $scope->getClassReflection();

if ($classReflection === null) {
return [];
}
$classReflection = $node->getClassReflection();

if (($classReflection->getNativeReflection()->getModifiers() & 65_536) !== 0) { // readonly class, since PHP 8.2
return [];
Expand Down
11 changes: 11 additions & 0 deletions tests/Rule/EnforceReadonlyPublicPropertyRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use PHPStan\Php\PhpVersion;
use PHPStan\Rules\Rule;
use ShipMonk\PHPStan\RuleTestCase;
use const PHP_VERSION_ID;

/**
* @extends RuleTestCase<EnforceReadonlyPublicPropertyRule>
Expand All @@ -20,6 +21,16 @@ protected function getRule(): Rule
return new EnforceReadonlyPublicPropertyRule($this->phpVersion);
}

public function testPhp84(): void
{
if (PHP_VERSION_ID < 8_00_00) {
self::markTestSkipped('PHP7 parser fails with property hooks');
}

$this->phpVersion = $this->createPhpVersion(80_400);
$this->analyseFile(__DIR__ . '/data/EnforceReadonlyPublicPropertyRule/code-84.php');
}

public function testPhp81(): void
{
$this->phpVersion = $this->createPhpVersion(80_100);
Expand Down
59 changes: 59 additions & 0 deletions tests/Rule/data/EnforceReadonlyPublicPropertyRule/code-84.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

namespace EnforceReadonlyPublicPropertyRule84;

trait MyTrait {

public ?string $public; // error: Public property `public` not marked as readonly.

public ?string $hooked { get => $this->hooked; }

public readonly string $publicReadonly;

protected string $protected;

private string $private;

}

class MyClass {

use MyTrait;

public ?int $foo; // error: Public property `foo` not marked as readonly.

public ?string $classHooked { set => strtolower($value); }

public readonly int $bar;

protected int $baz;

private int $bag;

}

readonly class MyReadonlyClass {

public ?int $foo;

public readonly int $bar;

public ?string $hooked { get => $this->hooked; }

protected int $baz;

private int $bag;

}

interface MyInterface {
public string $key { get; }
}

class ImplementingClass implements MyInterface {
public string $key; // error: Public property `key` not marked as readonly.
}

class ImplementingClass2 implements MyInterface {
public readonly string $key;
}