|
14 | 14 | use PhpParser\Node\Stmt\Class_; |
15 | 15 | use PhpParser\Node\Stmt\ClassMethod; |
16 | 16 | use PhpParser\Node\Stmt\Property; |
| 17 | +use PhpParser\Node\Stmt\Return_; |
17 | 18 | use PhpParser\NodeVisitor; |
18 | 19 | use PHPStan\Analyser\Scope; |
19 | 20 | use PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode; |
@@ -174,6 +175,11 @@ private function refactorProperty(Class_ $class, Property $property, Scope $scop |
174 | 175 | return null; |
175 | 176 | } |
176 | 177 |
|
| 178 | + // returned by reference can be mutated outside the class, so it cannot be readonly |
| 179 | + if ($this->isPropertyReturnedByRef($class, (string) $this->getName($property))) { |
| 180 | + return null; |
| 181 | + } |
| 182 | + |
177 | 183 | $this->visibilityManipulator->makeReadonly($property); |
178 | 184 | $this->removeReadOnlyDoc($property); |
179 | 185 |
|
@@ -236,13 +242,47 @@ private function refactorParam(Class_ $class, ClassMethod $classMethod, Param $p |
236 | 242 | return null; |
237 | 243 | } |
238 | 244 |
|
| 245 | + // returned by reference can be mutated outside the class, so it cannot be readonly |
| 246 | + if ($this->isPropertyReturnedByRef($class, (string) $this->getName($param))) { |
| 247 | + return null; |
| 248 | + } |
| 249 | + |
239 | 250 | $this->visibilityManipulator->makeReadonly($param); |
240 | 251 |
|
241 | 252 | $this->removeReadOnlyDoc($param); |
242 | 253 |
|
243 | 254 | return $param; |
244 | 255 | } |
245 | 256 |
|
| 257 | + private function isPropertyReturnedByRef(Class_ $class, string $propertyName): bool |
| 258 | + { |
| 259 | + foreach ($class->getMethods() as $classMethod) { |
| 260 | + if (! $classMethod->byRef) { |
| 261 | + continue; |
| 262 | + } |
| 263 | + |
| 264 | + $returns = $this->betterNodeFinder->findInstanceOf($classMethod, Return_::class); |
| 265 | + foreach ($returns as $return) { |
| 266 | + if (! $return->expr instanceof Expr) { |
| 267 | + continue; |
| 268 | + } |
| 269 | + |
| 270 | + $propertyFetch = $this->betterNodeFinder->findFirst( |
| 271 | + $return->expr, |
| 272 | + fn (Node $subNode): bool => $subNode instanceof PropertyFetch |
| 273 | + && $this->isName($subNode->var, 'this') |
| 274 | + && $this->isName($subNode, $propertyName) |
| 275 | + ); |
| 276 | + |
| 277 | + if ($propertyFetch instanceof PropertyFetch) { |
| 278 | + return true; |
| 279 | + } |
| 280 | + } |
| 281 | + } |
| 282 | + |
| 283 | + return false; |
| 284 | + } |
| 285 | + |
246 | 286 | private function isPromotedPropertyAssigned(Class_ $class, Param $param): bool |
247 | 287 | { |
248 | 288 | $constructClassMethod = $class->getMethod(MethodName::CONSTRUCT); |
|
0 commit comments