|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Buki\Commands; |
| 4 | + |
| 5 | +use Symfony\Component\Console\Command\Command; |
| 6 | +use Symfony\Component\Console\Input\InputArgument; |
| 7 | +use Symfony\Component\Console\Input\InputInterface; |
| 8 | +use Symfony\Component\Console\Output\OutputInterface; |
| 9 | + |
| 10 | +/** |
| 11 | + * Class CreateControllerCommand |
| 12 | + * |
| 13 | + * @package Buki\Commands |
| 14 | + */ |
| 15 | +class CreateControllerCommand extends Command |
| 16 | +{ |
| 17 | + protected static $defaultName = 'make:controller'; |
| 18 | + |
| 19 | + protected function configure() |
| 20 | + { |
| 21 | + $this->setDescription('Create a new Controller'); |
| 22 | + $this->addArgument('name', InputArgument::REQUIRED, 'Name of the controller'); |
| 23 | + $this->addArgument('path', InputArgument::OPTIONAL, 'Absolute path of the controller\'s directory'); |
| 24 | + $this->addArgument('namespace', InputArgument::OPTIONAL, 'Namespace of the controller directory'); |
| 25 | + } |
| 26 | + |
| 27 | + protected function execute(InputInterface $input, OutputInterface $output) |
| 28 | + { |
| 29 | + $className = $input->getArgument('name'); |
| 30 | + |
| 31 | + if (!is_dir($directory = $input->getArgument('path'))) { |
| 32 | + if (is_null($directory)) { |
| 33 | + $directory = explode('/vendor/', getcwd())[0] . '/Controllers'; |
| 34 | + |
| 35 | + $output->writeln([ |
| 36 | + '', |
| 37 | + 'Default directory is: ' . $directory, |
| 38 | + '', |
| 39 | + ]); |
| 40 | + } else { |
| 41 | + $output->writeln([ |
| 42 | + '', |
| 43 | + 'ERROR: The specified directory does not exist!', |
| 44 | + ]); |
| 45 | + |
| 46 | + exit; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + if (is_null($namespace = $input->getArgument('namespace'))) { |
| 51 | + $namespace = 'Controllers'; |
| 52 | + |
| 53 | + $output->writeln([ |
| 54 | + '', |
| 55 | + 'Default namespace is: ' . $namespace, |
| 56 | + '', |
| 57 | + ]); |
| 58 | + } |
| 59 | + |
| 60 | + try { |
| 61 | + ob_start(); |
| 62 | + echo '<?php'; |
| 63 | + include __DIR__ . '/ControllerTemplate.php'; |
| 64 | + $content = ob_get_contents(); |
| 65 | + ob_end_clean(); |
| 66 | + |
| 67 | + $filePath = $directory . "/{$className}.php"; |
| 68 | + |
| 69 | + if (is_file($filePath)) { |
| 70 | + throw new Exception("The controller already exists!"); |
| 71 | + } |
| 72 | + |
| 73 | + $file = fopen($filePath, 'w+'); |
| 74 | + |
| 75 | + file_put_contents($filePath, $content); |
| 76 | + fclose($file); |
| 77 | + |
| 78 | + $output->writeln([ |
| 79 | + '', |
| 80 | + 'SUCCESS!', |
| 81 | + ]); |
| 82 | + |
| 83 | + return Command::SUCCESS; |
| 84 | + } catch (\Exception $exception) { |
| 85 | + $output->writeln([ |
| 86 | + '', |
| 87 | + 'ERROR: ' . $exception->getMessage(), |
| 88 | + ]); |
| 89 | + |
| 90 | + return Command::FAILURE; |
| 91 | + } |
| 92 | + } |
| 93 | +} |
0 commit comments