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
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Rector\Tests\Php81\Rector\Property\ReadOnlyPropertyRector\Fixture;

final class SkipReturnedByRef
{
public function __construct(
private array $byLine = [],
) {
}

public function &getByLine(): array
{
return $this->byLine;
}
}
40 changes: 40 additions & 0 deletions rules/Php81/Rector/Property/ReadOnlyPropertyRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Property;
use PhpParser\Node\Stmt\Return_;
use PhpParser\NodeVisitor;
use PHPStan\Analyser\Scope;
use PHPStan\PhpDocParser\Ast\PhpDoc\GenericTagValueNode;
Expand Down Expand Up @@ -174,6 +175,11 @@ private function refactorProperty(Class_ $class, Property $property, Scope $scop
return null;
}

// returned by reference can be mutated outside the class, so it cannot be readonly
if ($this->isPropertyReturnedByRef($class, (string) $this->getName($property))) {
return null;
}

$this->visibilityManipulator->makeReadonly($property);
$this->removeReadOnlyDoc($property);

Expand Down Expand Up @@ -236,13 +242,47 @@ private function refactorParam(Class_ $class, ClassMethod $classMethod, Param $p
return null;
}

// returned by reference can be mutated outside the class, so it cannot be readonly
if ($this->isPropertyReturnedByRef($class, (string) $this->getName($param))) {
return null;
}

$this->visibilityManipulator->makeReadonly($param);

$this->removeReadOnlyDoc($param);

return $param;
}

private function isPropertyReturnedByRef(Class_ $class, string $propertyName): bool
{
foreach ($class->getMethods() as $classMethod) {
if (! $classMethod->byRef) {
continue;
}

$returns = $this->betterNodeFinder->findInstanceOf($classMethod, Return_::class);
foreach ($returns as $return) {
if (! $return->expr instanceof Expr) {
continue;
}

$propertyFetch = $this->betterNodeFinder->findFirst(
$return->expr,
fn (Node $subNode): bool => $subNode instanceof PropertyFetch
&& $this->isName($subNode->var, 'this')
&& $this->isName($subNode, $propertyName)
);

if ($propertyFetch instanceof PropertyFetch) {
return true;
}
}
}

return false;
}

private function isPromotedPropertyAssigned(Class_ $class, Param $param): bool
{
$constructClassMethod = $class->getMethod(MethodName::CONSTRUCT);
Expand Down
Loading