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
Expand Up @@ -2,7 +2,7 @@

namespace Rector\Tests\Unambiguous\Rector\Expression\FluentSettersToStandaloneCallMethodRector\Source;

class SomeSetterClass
final class SomeSetterClass
{
private ?string $name = null;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use PhpParser\Node\Expr\New_;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Return_;
use PHPStan\Reflection\ClassReflection;
Expand Down Expand Up @@ -113,35 +114,19 @@ public function refactor(Node $node): ?array
}

$rootExpr = $currentMethodCall;
if (! $rootExpr instanceof New_) {
return null;
}

if ($this->shouldSkipForVendorOrInternal($firstMethodCall)) {
return null;
}

$variableName = $this->resolveVariableName($rootExpr);
$someVariable = new Variable($variableName);

$firstAssign = new Assign($someVariable, $rootExpr);
$stmts = [new Expression($firstAssign)];

// revert to normal order
$methodCalls = array_reverse($methodCalls);

foreach ($methodCalls as $methodCall) {
$methodCall->var = $someVariable;
// inlines indent and removes () around first expr
$methodCall->setAttribute(AttributeKey::ORIGINAL_NODE, null);
$stmts[] = new Expression($methodCall);
}

if ($node instanceof Return_) {
$node->expr = $someVariable;
$stmts[] = $node;
}

$node->expr = $someVariable;

return $stmts;
return $this->createStmts($firstAssign, $methodCalls, $someVariable, $node);
}

private function resolveVariableName(Expr $expr): string
Expand Down Expand Up @@ -174,4 +159,36 @@ private function shouldSkipForVendorOrInternal(MethodCall $firstMethodCall): boo

return false;
}

/**
* @param MethodCall[] $methodCalls
* @return Stmt[]
*/
private function createStmts(
Assign $firstAssign,
array $methodCalls,
Variable $someVariable,
Expression|Return_ $firstStmt
): array {
$stmts = [new Expression($firstAssign)];

// revert to normal order
$methodCalls = array_reverse($methodCalls);

foreach ($methodCalls as $methodCall) {
$methodCall->var = $someVariable;
// inlines indent and removes () around first expr
$methodCall->setAttribute(AttributeKey::ORIGINAL_NODE, null);
$stmts[] = new Expression($methodCall);
}

if ($firstStmt instanceof Return_) {
$firstStmt->expr = $someVariable;
$stmts[] = $firstStmt;
}

$firstStmt->expr = $someVariable;

return $stmts;
}
}