Skip to content

Commit 9e24fa2

Browse files
committed
Report accessing private properties on non-final classes in ?? condition
1 parent 802fa6e commit 9e24fa2

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

src/Rules/Properties/AccessPropertiesCheck.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,13 @@ private function processSingleProperty(Scope $scope, PropertyFetch $node, string
240240
|| !$write
241241
|| (!$propertyReflection->isPrivateSet() && !$propertyReflection->isProtectedSet())
242242
) {
243+
if (
244+
$scope->isUndefinedExpressionAllowed($node)
245+
&& !$propertyReflection->getDeclaringClass()->isFinal()
246+
) {
247+
return [];
248+
}
249+
243250
return [
244251
RuleErrorBuilder::message(sprintf(
245252
'Access to %s property %s::$%s.',

tests/PHPStan/Rules/Properties/AccessPropertiesRuleTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1144,4 +1144,25 @@ public function testBug11424(): void
11441144
]);
11451145
}
11461146

1147+
public function testBug12645(): void
1148+
{
1149+
$this->checkThisOnly = false;
1150+
$this->checkUnionTypes = true;
1151+
$this->checkDynamicProperties = false;
1152+
$this->analyse([__DIR__ . '/data/bug-12645.php'], [
1153+
[
1154+
'Access to private property Bug12645\Foo::$id.',
1155+
18,
1156+
],
1157+
[
1158+
'Access to private property Bug12645\Foo::$id.',
1159+
19,
1160+
],
1161+
[
1162+
'Access to private property Bug12645\Foo::$id.',
1163+
24,
1164+
],
1165+
]);
1166+
}
1167+
11471168
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
namespace Bug12645;
4+
5+
class Foo
6+
{
7+
private int $id = 1;
8+
9+
public function getId(): int
10+
{
11+
return $this->id;
12+
}
13+
}
14+
15+
function (): void {
16+
$foo = new Foo();
17+
18+
var_dump($foo->id ?? 2);
19+
var_dump($foo->id);
20+
};
21+
22+
function (Foo $foo): void {
23+
var_dump($foo->id ?? 2);
24+
var_dump($foo->id);
25+
};

0 commit comments

Comments
 (0)