|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace DragonCode\LaravelHttpMacros\Commands; |
| 6 | + |
| 7 | +use DragonCode\LaravelHttpMacros\Macros\Macro; |
| 8 | +use DragonCode\Support\Facades\Filesystem\Directory; |
| 9 | +use DragonCode\Support\Facades\Filesystem\File; |
| 10 | +use Illuminate\Console\Command; |
| 11 | +use Illuminate\Support\Str; |
| 12 | + |
| 13 | +class GenerateHelperCommand extends Command |
| 14 | +{ |
| 15 | + protected $signature = 'http:macros-helper'; |
| 16 | + |
| 17 | + protected $description = 'Generates correct PHPDocs for Http facade macros'; |
| 18 | + |
| 19 | + public function handle(): void |
| 20 | + { |
| 21 | + $names = $this->names(); |
| 22 | + |
| 23 | + $static = $this->make($names, true); |
| 24 | + $dynamic = $this->make($names); |
| 25 | + |
| 26 | + $this->cleanUp(); |
| 27 | + $this->store($static, true); |
| 28 | + $this->store($dynamic); |
| 29 | + } |
| 30 | + |
| 31 | + protected function make(array $names, bool $isStatic = false): array |
| 32 | + { |
| 33 | + return array_map( |
| 34 | + fn (string $name) => sprintf( |
| 35 | + ' * @method %s $this %s(\Closure|string $class, int|string|null $key = null)', |
| 36 | + $isStatic ? 'static' : '', |
| 37 | + $name |
| 38 | + ), |
| 39 | + $names |
| 40 | + ); |
| 41 | + } |
| 42 | + |
| 43 | + protected function store(array $methods, bool $isStatic = false): void |
| 44 | + { |
| 45 | + File::store( |
| 46 | + $this->path($this->filename($isStatic)), |
| 47 | + $this->makeDocBlock($methods) |
| 48 | + ); |
| 49 | + } |
| 50 | + |
| 51 | + protected function makeDocBlock(array $methods): string |
| 52 | + { |
| 53 | + return Str::replace('{methods}', implode(PHP_EOL, $methods), $this->template()); |
| 54 | + } |
| 55 | + |
| 56 | + protected function names(): array |
| 57 | + { |
| 58 | + return collect($this->macros())->map( |
| 59 | + fn (Macro|string $macro, int|string $name) => is_string($name) ? $name : $macro::name() |
| 60 | + )->all(); |
| 61 | + } |
| 62 | + |
| 63 | + protected function path(?string $filename = null): string |
| 64 | + { |
| 65 | + return base_path('vendor/_http_macros/' . $filename); |
| 66 | + } |
| 67 | + |
| 68 | + protected function filename(bool $isStatic): string |
| 69 | + { |
| 70 | + return $isStatic |
| 71 | + ? '_ide_helper_macro_static.php' |
| 72 | + : '_ide_helper_macro.php'; |
| 73 | + } |
| 74 | + |
| 75 | + protected function cleanUp(): void |
| 76 | + { |
| 77 | + Directory::ensureDelete($this->path()); |
| 78 | + } |
| 79 | + |
| 80 | + protected function macros(): array |
| 81 | + { |
| 82 | + return config('http.macros.response', []); |
| 83 | + } |
| 84 | + |
| 85 | + protected function template(): string |
| 86 | + { |
| 87 | + return file_get_contents(__DIR__ . '/../../stubs/helper.stub'); |
| 88 | + } |
| 89 | +} |
0 commit comments