Skip to content

Instantly share code, notes, and snippets.

@osbre
Last active September 15, 2023 11:18
Show Gist options
  • Save osbre/cdb8716a504328a9a08e9e7fa3250c7e to your computer and use it in GitHub Desktop.
Save osbre/cdb8716a504328a9a08e9e7fa3250c7e to your computer and use it in GitHub Desktop.
Laravel Shift broke the project by adding return types to controller methods when upgrading to Laravel 10. This rector removes the return types from the controller methods.
<?php
namespace App\Rector;
use Illuminate\Routing\Controller;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
* Laravel Shift broke the project by adding return types to controller methods when upgrading to Laravel 10.
* This rector removes the return types from the controller methods.
*
* @author Ostap Brehin
* @see https://github.com/rectorphp/rector
*/
final class RemoveReturnTypesFromControllersRector extends AbstractRector
{
public function getNodeTypes(): array
{
return [Class_::class];
}
/**
* @param Class_ $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->shouldRefactorClass($node)) {
return null;
}
/** @var Class_ $node */
foreach ($node->getMethods() as $method) {
if (! $method->isPublic()) {
continue;
}
$method->returnType = null;
}
return $node;
}
private function shouldRefactorClass(Class_ $class): bool
{
if (str_ends_with((string)$class->name, 'Controller')) {
return true;
}
return in_array((string)$class->extends, [
Controller::class,
\App\Http\Controllers\Controller::class,
]);
}
public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Remove return types from public methods in controllers',
[
new CodeSample(
<<<'CODE_SAMPLE'
class ArticleController extends Controller {
public function show(): Response
{
return view('articles.show');
}
}
CODE_SAMPLE
,
<<<'CODE_SAMPLE'
class ArticleController extends Controller {
public function show()
{
return view('articles.show');
}
}
CODE_SAMPLE
),
]
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment