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 SkipChangedByRefInForeach
{
private array $relativeDateStrings;

public function __construct()
{
$this->relativeDateStrings = ['yesterday', 'today'];
foreach ($this->relativeDateStrings as &$string) {
$string = strtoupper($string);
}
}
}
31 changes: 31 additions & 0 deletions rules/Php81/Rector/Property/ReadOnlyPropertyRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use PhpParser\Node\Param;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Foreach_;
use PhpParser\Node\Stmt\Property;
use PhpParser\Node\Stmt\Return_;
use PhpParser\NodeVisitor;
Expand Down Expand Up @@ -180,6 +181,11 @@ private function refactorProperty(Class_ $class, Property $property, Scope $scop
return null;
}

// changed via reference in foreach, e.g. foreach ($this->items as &$item), so it cannot be readonly
if ($this->isPropertyChangedInByRefForeach($class, (string) $this->getName($property))) {
return null;
}

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

Expand Down Expand Up @@ -247,6 +253,11 @@ private function refactorParam(Class_ $class, ClassMethod $classMethod, Param $p
return null;
}

// changed via reference in foreach, e.g. foreach ($this->items as &$item), so it cannot be readonly
if ($this->isPropertyChangedInByRefForeach($class, (string) $this->getName($param))) {
return null;
}

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

$this->removeReadOnlyDoc($param);
Expand Down Expand Up @@ -283,6 +294,26 @@ private function isPropertyReturnedByRef(Class_ $class, string $propertyName): b
return false;
}

private function isPropertyChangedInByRefForeach(Class_ $class, string $propertyName): bool
{
return (bool) $this->betterNodeFinder->findFirst($class, function (Node $node) use ($propertyName): bool {
if (! $node instanceof Foreach_) {
return false;
}

if (! $node->byRef) {
return false;
}

if (! $node->expr instanceof PropertyFetch) {
return false;
}

return $this->isName($node->expr->var, 'this')
&& $this->isName($node->expr, $propertyName);
});
}

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