|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Rappasoft\LaravelLivewireTables\Commands; |
| 4 | + |
| 5 | +use Illuminate\Console\Command; |
| 6 | +use Illuminate\Support\Facades\File; |
| 7 | +use Livewire\Commands\ComponentParser; |
| 8 | +use Livewire\Commands\MakeCommand as LivewireMakeCommand; |
| 9 | + |
| 10 | +class MakeCommand extends Command |
| 11 | +{ |
| 12 | + protected $parser; |
| 13 | + /** |
| 14 | + * The name and signature of the console command. |
| 15 | + * |
| 16 | + * @var string |
| 17 | + */ |
| 18 | + protected $signature = 'make:table {name} {--force}'; |
| 19 | + |
| 20 | + /** |
| 21 | + * The console command description. |
| 22 | + * |
| 23 | + * @var string |
| 24 | + */ |
| 25 | + protected $description = 'Generate a Laravel Livewire table class and view'; |
| 26 | + |
| 27 | + public function handle() |
| 28 | + { |
| 29 | + $this->parser = new ComponentParser( |
| 30 | + config('livewire.class_namespace'), |
| 31 | + config('livewire.view_path'), |
| 32 | + $this->argument('name') |
| 33 | + ); |
| 34 | + |
| 35 | + $livewireMakeCommand = new LivewireMakeCommand(); |
| 36 | + |
| 37 | + if($livewireMakeCommand->isReservedClassName($name = $this->parser->className())) { |
| 38 | + $this->line("<options=bold,reverse;fg=red> WHOOPS! </> 😳 \n"); |
| 39 | + $this->line("<fg=red;options=bold>Class is reserved:</> {$name}"); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + $force = $this->option('force'); |
| 44 | + |
| 45 | + $this->createClass($force); |
| 46 | + |
| 47 | + $this->info('Livewire Datatable Created: ' . $this->parser->className()); |
| 48 | + } |
| 49 | + |
| 50 | + protected function createClass($force = false) |
| 51 | + { |
| 52 | + $classPath = $this->parser->classPath(); |
| 53 | + |
| 54 | + if (File::exists($classPath) && ! $force) { |
| 55 | + $this->line("<options=bold,reverse;fg=red> WHOOPS-IE-TOOTLES </> 😳 \n"); |
| 56 | + $this->line("<fg=red;options=bold>Class already exists:</> {$this->parser->relativeClassPath()}"); |
| 57 | + |
| 58 | + return false; |
| 59 | + } |
| 60 | + |
| 61 | + $this->ensureDirectoryExists($classPath); |
| 62 | + |
| 63 | + File::put($classPath, $this->classContents()); |
| 64 | + |
| 65 | + return $classPath; |
| 66 | + } |
| 67 | + |
| 68 | + protected function ensureDirectoryExists($path) |
| 69 | + { |
| 70 | + if (! File::isDirectory(dirname($path))) { |
| 71 | + File::makeDirectory(dirname($path), 0777, $recursive = true, $force = true); |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + public function classContents() |
| 76 | + { |
| 77 | + $template = file_get_contents(__DIR__.DIRECTORY_SEPARATOR.'table.stub'); |
| 78 | + |
| 79 | + return preg_replace_array( |
| 80 | + ['/\[namespace\]/', '/\[class\]/'], |
| 81 | + [$this->parser->classNamespace(), $this->parser->className()], |
| 82 | + $template |
| 83 | + ); |
| 84 | + } |
| 85 | +} |
0 commit comments