setName('create:module') ->addArgument('module', Argument::REQUIRED, 'module name') ->setDescription('create module service'); } protected function execute(Input $input, Output $output) { try { $this->module = strtolower($input->getArgument('module')); $this->moduleDir = CatchAdmin::moduleDirectory($this->module); $this->stubDir = __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR; $composer = json_decode(file_get_contents($this->app->getRootPath() . 'composer.json'), true); $psr4 = $composer['autoload']['psr-4']; foreach ($psr4 as $namespace => $des) { if ($des === CatchAdmin::NAME) { $this->namespaces = $namespace . $this->module . '\\'; break; } } $this->createFile(); } catch (\Exception $exception) { $this->rollback(); $output->error($exception->getMessage()); exit; } $output->info('module created'); } /** * 创建失败 rollback * * @time 2020年06月25日 * @return void */ protected function rollback() { (new Compress())->rmDir($this->moduleDir); } /** * 模块文件夹 * * @time 2020年06月25日 * @return string[] */ protected function modulePath() { return [ $this->moduleDir . 'controller', $this->moduleDir . 'model', $this->moduleDir . 'database' . DIRECTORY_SEPARATOR . 'migrations', $this->moduleDir . 'database' . DIRECTORY_SEPARATOR . 'seeds', ]; } /** * 模块文件 * * @time 2020年06月25日 * @return string[] */ protected function moduleFiles() { return [ $this->moduleDir . ucfirst($this->module). 'Service.php', $this->moduleDir . 'module.json', $this->moduleDir . 'route.php', ]; } /** * 创建路径 * * @time 2020年06月25日 * @return void */ protected function createDir() { foreach ($this->modulePath() as $path) { CatchAdmin::makeDirectory($path); } } /** * 创建文件 * * @time 2020年06月25日 * @return void */ protected function createFile() { $this->createDir(); $this->createService(); $this->createRoute(); $this->createModuleJson(); } /** * 创建 service * * @time 2020年06月25日 * @return void */ protected function createService() { $service = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'service.stub'); $content = str_replace(['{NAMESPACE}', '{SERVICE}'], [substr($this->namespaces, 0, -1), ucfirst($this->module) . 'Service'], $service); file_put_contents($this->moduleDir . ucfirst($this->module) . 'Service.php', $content); } /** * 创建 module.json * * @time 2020年06月25日 * @return void */ protected function createModuleJson() { $moduleJson = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'module.stub'); $content = str_replace(['{MODULE}', '{SERVICE}'], [$this->module, '\\\\'. str_replace('\\', '\\\\',$this->namespaces . ucfirst($this->module) . 'Service')], $moduleJson); file_put_contents($this->moduleDir . 'module.json', $content); } /** * 创建路由文件 * * @time 2020年06月25日 * @return void */ protected function createRoute() { file_put_contents($this->moduleDir . 'route.php', file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'route.stub')); } }