|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PDPhilip\Elasticsearch\Commands; |
| 6 | + |
| 7 | +use Illuminate\Console\GeneratorCommand; |
| 8 | +use Illuminate\Support\Str; |
| 9 | +use OmniTerm\HasOmniTerm; |
| 10 | + |
| 11 | +class MakeCommand extends GeneratorCommand |
| 12 | +{ |
| 13 | + use HasOmniTerm; |
| 14 | + |
| 15 | + protected $signature = 'elastic:make {name : The name of the Elasticsearch model}'; |
| 16 | + |
| 17 | + protected $description = 'Create a new Elasticsearch model'; |
| 18 | + |
| 19 | + protected $type = 'Model'; |
| 20 | + |
| 21 | + public function handle(): int |
| 22 | + { |
| 23 | + $name = Str::studly($this->argument('name')); |
| 24 | + |
| 25 | + $namespace = $this->resolveNamespace($name); |
| 26 | + $class = class_basename(str_replace('/', '\\', $name)); |
| 27 | + $fullClass = $namespace.'\\'.$class; |
| 28 | + $path = $this->getModelPath($name); |
| 29 | + |
| 30 | + if (file_exists($path)) { |
| 31 | + $this->newLine(); |
| 32 | + $this->omni->statusError('Model already exists', $fullClass); |
| 33 | + $this->newLine(); |
| 34 | + |
| 35 | + return self::FAILURE; |
| 36 | + } |
| 37 | + |
| 38 | + $this->makeDirectory($path); |
| 39 | + |
| 40 | + $stub = $this->buildStub($namespace, $class); |
| 41 | + $this->files->put($path, $stub); |
| 42 | + |
| 43 | + $this->newLine(); |
| 44 | + $this->omni->statusSuccess('Model created', $fullClass); |
| 45 | + $this->omni->tableRow('Path', str_replace(base_path().'/', '', $path)); |
| 46 | + $this->newLine(); |
| 47 | + |
| 48 | + return self::SUCCESS; |
| 49 | + } |
| 50 | + |
| 51 | + protected function getStub(): string |
| 52 | + { |
| 53 | + return __DIR__.'/../../resources/stubs/ElasticModel.php.stub'; |
| 54 | + } |
| 55 | + |
| 56 | + private function resolveNamespace(string $name): string |
| 57 | + { |
| 58 | + $parts = explode('/', str_replace('\\', '/', $name)); |
| 59 | + array_pop($parts); |
| 60 | + |
| 61 | + $sub = implode('\\', $parts); |
| 62 | + |
| 63 | + return $sub |
| 64 | + ? 'App\\Models\\'.$sub |
| 65 | + : 'App\\Models'; |
| 66 | + } |
| 67 | + |
| 68 | + private function getModelPath(string $name): string |
| 69 | + { |
| 70 | + $name = str_replace('\\', '/', $name); |
| 71 | + |
| 72 | + return app_path('Models/'.$name.'.php'); |
| 73 | + } |
| 74 | + |
| 75 | + private function buildStub(string $namespace, string $class): string |
| 76 | + { |
| 77 | + $stub = $this->files->get($this->getStub()); |
| 78 | + |
| 79 | + return str_replace( |
| 80 | + ['{{ namespace }}', '{{ class }}'], |
| 81 | + [$namespace, $class], |
| 82 | + $stub |
| 83 | + ); |
| 84 | + } |
| 85 | +} |
0 commit comments