Created
August 1, 2024 16:10
-
-
Save AnandPilania/3693b69cfd5bd40a0bf97988df97f5d3 to your computer and use it in GitHub Desktop.
Laravel: find missing methods in reaource routes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Console\Commands; | |
use Illuminate\Console\Command; | |
use Illuminate\Support\Facades\Route; | |
use ReflectionClass; | |
class CheckResourceRoutesCommand extends Command | |
{ | |
/** | |
* @var string | |
*/ | |
protected $signature = 'route:check-resources'; | |
/** | |
* @var string | |
*/ | |
protected $description = 'Find missing methods in resource routes'; | |
public function handle(): void | |
{ | |
$resourceRoutes = collect(Route::getRoutes())->filter(function ($route) { | |
return $route->getActionName() !== 'Closure' && | |
strpos($route->getActionName(), '@') !== false; | |
}); | |
$missingMethods = []; | |
foreach ($resourceRoutes as $route) { | |
$action = $route->getActionName(); | |
[$controller, $method] = explode('@', $action); | |
if (!class_exists($controller)) { | |
$missingMethods[$controller][] = ['method' => $method, 'uri' => $route->uri()]; | |
continue; | |
} | |
$reflection = new ReflectionClass($controller); | |
if (!$reflection->hasMethod($method)) { | |
$missingMethods[$controller][] = ['method' => $method, 'uri' => $route->uri()]; | |
} | |
} | |
if (empty($missingMethods)) { | |
$this->info('All resource routes have matching controller methods.'); | |
} else { | |
$this->info('The following resource routes do not have a matching matching controller method.'); | |
foreach ($missingMethods as $controller => $methods) { | |
$this->warn("Controller: $controller"); | |
foreach ($methods as $method) { | |
$this->line(" - Method: {$method['method']}, URI: {$method['uri']}"); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment