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
26 changes: 15 additions & 11 deletions src/Rector/MethodCall/EloquentOrderByToLatestOrOldestRector.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,10 @@ private function convertOrderByToLatest(MethodCall $methodCall): MethodCall
return $methodCall;
}

if (isset($methodCall->args[1]) && (! $methodCall->args[1] instanceof Arg || ! $methodCall->args[1]->value instanceof String_)) {
return $methodCall;
}

if (isset($methodCall->args[1]) && $methodCall->args[1] instanceof Arg && $methodCall->args[1]->value instanceof String_) {
$direction = $methodCall->args[1]->value->value;
} else {
Expand All @@ -164,22 +168,22 @@ private function convertOrderByToLatest(MethodCall $methodCall): MethodCall
} else {
$newMethod = $direction === 'asc' ? 'oldest' : 'latest';
}
if ($columnVar instanceof String_ && $columnVar->value === 'created_at') {
$methodCall->name = new Identifier($newMethod);
$methodCall->args = [];

return $methodCall;
}

if ($columnVar instanceof String_) {
$methodCall->name = new Identifier($newMethod);
$methodCall->args = [new Arg(new String_($columnVar->value))];
return $this->createMethodCall($methodCall, $newMethod, $columnVar);
}

return $methodCall;
private function createMethodCall(MethodCall $methodCall, string $newMethod, Expr $expr): MethodCall
{
if ($expr instanceof String_ && $expr->value === 'created_at') {
$args = [];
} elseif ($expr instanceof String_) {
$args = [new Arg(new String_($expr->value))];
} else {
$args = [new Arg($expr)];
}

$methodCall->name = new Identifier($newMethod);
$methodCall->args = [new Arg($columnVar)];
$methodCall->args = $args;

return $methodCall;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

namespace RectorLaravel\Tests\Rector\Cast\DatabaseExpressionCastsToMethodCall\Fixture;

use Illuminate\Database\Query\Builder;

$asc = 'asc';

/** @var Builder $query */
$query->orderBy('created_at', $asc);

?>