Skip to content

Instantly share code, notes, and snippets.

@zach2825
Created January 24, 2024 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zach2825/fcb3d8419cbecd5160474348bf0590bb to your computer and use it in GitHub Desktop.
Save zach2825/fcb3d8419cbecd5160474348bf0590bb to your computer and use it in GitHub Desktop.
ModelListCommand.php
<?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