Created
January 24, 2024 13:23
-
-
Save zach2825/fcb3d8419cbecd5160474348bf0590bb to your computer and use it in GitHub Desktop.
ModelListCommand.php
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 File; | |
use Illuminate\Console\Command; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Support\Str; | |
use ReflectionClass; | |
use ReflectionException; | |
class ModelsListCommand extends Command | |
{ | |
/** | |
* The name and signature of the console command. | |
* | |
* @var string | |
*/ | |
protected $signature = 'models:list {--s|search= : Search for a specific model}'; | |
/** | |
* The console command description. | |
* | |
* @var string | |
*/ | |
protected $description = 'Simple list of all the models in your app/Models directory.'; | |
/** | |
* Execute the console command. | |
* | |
* @throws ReflectionException | |
*/ | |
public function handle() | |
{ | |
$directoriesToScan = $this->getDirectoriesToScan(); | |
$models = collect($directoriesToScan) | |
->flatMap(fn ($directory) => File::allFiles($directory)) | |
// if search is passed in | |
->when($this->option('search'), fn ($files) => $files->filter(fn ($file) => Str::contains(mb_strtolower($file->getFilename()), mb_strtolower($this->option('search'))))) | |
->map(fn ($file) => $file->getPathname()) | |
->filter(fn ($path) => Str::endsWith($path, '.php')) | |
// remove the base path from the beginning of the path | |
->map(function ($path) { | |
return app()->getNamespace() . str_replace( | |
['/', '.php'], | |
['\\', ''], | |
Str::after($path, realpath(app_path()) . DIRECTORY_SEPARATOR) | |
); | |
}) | |
// remove the base namespace from the beginning of the class name | |
->filter(fn ($class) => class_exists($class)) | |
// make sure they are only models | |
->filter(function ($class) { | |
$reflection = new ReflectionClass($class); | |
return $reflection->isSubclassOf(Model::class) && ! $reflection->isAbstract(); | |
}) | |
->values(); | |
$this->output($models); | |
return self::SUCCESS; | |
} | |
public function getDirectoriesToScan() | |
{ | |
return [ | |
app_path('Models'), | |
]; | |
} | |
public function output($models) | |
{ | |
$this->table( | |
headers: ['Model', 'Name'], | |
rows: $models->map( | |
fn ($model) => [ | |
$model, | |
Str::replace('App\\Models\\', '', $model), | |
] | |
) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment