Skip to content

Commit da73771

Browse files
committed
UnusedPrivatePropertyRule - handle virtual properties that can only be read or only written
1 parent 8d4796d commit da73771

File tree

4 files changed

+59
-2
lines changed

4 files changed

+59
-2
lines changed

src/Node/ClassPropertyNode.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,4 +170,14 @@ public function isVirtual(): bool
170170
return $this->classReflection->getNativeProperty($this->name)->isVirtual()->yes();
171171
}
172172

173+
public function isWritable(): bool
174+
{
175+
return $this->classReflection->getNativeProperty($this->name)->isWritable();
176+
}
177+
178+
public function isReadable(): bool
179+
{
180+
return $this->classReflection->getNativeProperty($this->name)->isReadable();
181+
}
182+
173183
}

src/Rules/DeadCode/UnusedPrivatePropertyRule.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,8 @@ public function processNode(Node $node, Scope $scope): array
5959
continue;
6060
}
6161

62-
$alwaysRead = false;
63-
$alwaysWritten = false;
62+
$alwaysRead = !$property->isReadable();
63+
$alwaysWritten = !$property->isWritable();
6464
if ($property->getPhpDoc() !== null) {
6565
$text = $property->getPhpDoc();
6666
foreach ($this->alwaysReadTags as $tag) {

tests/PHPStan/Rules/DeadCode/UnusedPrivatePropertyRuleTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,4 +399,16 @@ public function testBug12621(): void
399399
$this->analyse([__DIR__ . '/data/bug-12621.php'], []);
400400
}
401401

402+
public function testBug12702(): void
403+
{
404+
if (PHP_VERSION_ID < 80400) {
405+
$this->markTestSkipped('Test requires PHP 8.4.');
406+
}
407+
408+
$this->alwaysWrittenTags = [];
409+
$this->alwaysReadTags = [];
410+
411+
$this->analyse([__DIR__ . '/data/bug-12702.php'], []);
412+
}
413+
402414
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php // lint >= 8.4
2+
3+
namespace Bug12702;
4+
5+
class Foo
6+
{
7+
/**
8+
* @var string[]
9+
*/
10+
public array $x = [];
11+
private ?string $i { get => $this->x[$this->k] ?? null; }
12+
private int $k = 0;
13+
14+
public function x(): void {
15+
echo $this->i;
16+
}
17+
}
18+
19+
class Bar
20+
{
21+
/**
22+
* @var string[]
23+
*/
24+
public array $x = [];
25+
private ?string $i {
26+
set {
27+
$this->x[$this->k] = $value;
28+
}
29+
}
30+
private int $k = 0;
31+
32+
public function x(): void {
33+
$this->i = 'foo';
34+
}
35+
}

0 commit comments

Comments
 (0)