|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace librarianphp\Create; |
| 6 | + |
| 7 | +use Minicli\Command\CommandController as MiniCliCommandController; |
| 8 | +use Minicli\Input; |
| 9 | + |
| 10 | +class CommandController extends MiniCliCommandController |
| 11 | +{ |
| 12 | + public function handle(): void |
| 13 | + { |
| 14 | + $input = new Input(' '); |
| 15 | + |
| 16 | + $this->info('Command: '); |
| 17 | + $command = $input->read(); |
| 18 | + |
| 19 | + $this->createCommandFile($this->buildCommandPath($command), $command); |
| 20 | + } |
| 21 | + |
| 22 | + private function buildCommandPath(string $command): array |
| 23 | + { |
| 24 | + $commandsPath = realpath($this->config->app_path[0]); |
| 25 | + $commandArray = explode(' ', $command); |
| 26 | + $commandPartsCount = count($commandArray); |
| 27 | + if ($commandPartsCount > 2) { |
| 28 | + $this->error('Command name must be one or two words.'); |
| 29 | + |
| 30 | + return []; |
| 31 | + } |
| 32 | + |
| 33 | + $commandPath = []; |
| 34 | + |
| 35 | + do { |
| 36 | + $commandPart = array_shift($commandArray); |
| 37 | + $commandPart = ucfirst(strtolower($commandPart)); |
| 38 | + $commandPath[] = $commandPart; |
| 39 | + |
| 40 | + if (count($commandArray) === 0 && $commandPartsCount > 1) { |
| 41 | + break; |
| 42 | + } |
| 43 | + |
| 44 | + $dir = "{$commandsPath}/" . implode('/', $commandPath); |
| 45 | + if (! is_dir($dir)) { |
| 46 | + mkdir($dir); |
| 47 | + } |
| 48 | + } while (count($commandArray) > 0); |
| 49 | + |
| 50 | + return array_map(fn ($item) => ucfirst(strtolower($item)), $commandPath); |
| 51 | + } |
| 52 | + |
| 53 | + private function createCommandFile(array $commandPath, string $command): void |
| 54 | + { |
| 55 | + if ($commandPath === []) { |
| 56 | + return; |
| 57 | + } |
| 58 | + $commandsPath = realpath($this->config->app_path[0]); |
| 59 | + $commandName = count($commandPath) > 1 ? array_pop($commandPath) : 'Default'; |
| 60 | + $commandClass = "{$commandName}Controller"; |
| 61 | + $commandFilePath = realpath("{$commandsPath}/" . implode('/', $commandPath)) . "/{$commandClass}.php"; |
| 62 | + |
| 63 | + if (file_exists($commandFilePath)) { |
| 64 | + $this->error("Command file already exists at {$commandFilePath}"); |
| 65 | + |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + $commandNamespace = 'namespace App\Command' . '\\' . implode('\\', $commandPath); |
| 70 | + $commandFileContent = file_get_contents(__DIR__ . '/../../stubs/command.stub'); |
| 71 | + $commandFileContent = str_replace( |
| 72 | + ['{{command_namespace}}', '{{command_class}}', '{{command_name}}'], |
| 73 | + [$commandNamespace, $commandClass, $command], |
| 74 | + $commandFileContent |
| 75 | + ); |
| 76 | + |
| 77 | + file_put_contents($commandFilePath, $commandFileContent); |
| 78 | + |
| 79 | + $this->success("{$command} command created!"); |
| 80 | + } |
| 81 | +} |
0 commit comments