diff --git a/src/Commands/InitCommand.php b/src/Commands/InitCommand.php index ebd3be6..46ab600 100644 --- a/src/Commands/InitCommand.php +++ b/src/Commands/InitCommand.php @@ -18,6 +18,10 @@ class InitCommand extends Command implements Isolatable { + protected $signature = 'init {application-name : The application name }'; + + protected $description = 'Initialize required project parameters to run DEV environment'; + public const array RESOURCES_ITEMS = [ 'issue_tracker' => 'Issue Tracker', 'figma' => 'Figma', @@ -42,20 +46,10 @@ class InitCommand extends Command implements Isolatable 'nova', ]; - protected $signature = 'init {application-name : The application name }'; - - protected $description = 'Initialize required project parameters to run DEV environment'; - - protected string $codeOwnerEmail; - protected array $resources = []; protected array $adminCredentials = []; - protected AuthTypeEnum $authType; - - protected string $appUrl; - protected array $emptyValuesList = []; protected array $shellCommands = [ @@ -72,16 +66,23 @@ class InitCommand extends Command implements Isolatable ]; protected bool $shouldUninstallPackage = false; + protected bool $shouldGenerateReadme; protected string $appName; - - protected string $dbConnection = 'pgsql'; - protected string $dbHost = 'pgsql'; - protected string $dbPort = '5432'; - protected string $dbName = 'postgres'; - protected string $dbUserName = 'postgres'; - + protected string $kebabName; + protected string $appUrl; protected AppTypeEnum $appType; + protected AuthTypeEnum $authType; + protected string $codeOwnerEmail; + + protected string $envFile; + protected array $envConfig = [ + 'dbConnection' => 'pgsql', + 'dbHost' => 'pgsql', + 'dbPort' => '5432', + 'dbName' => 'postgres', + 'dbUserName' => 'postgres', + ]; public function __construct( protected ReadmeGenerator $readmeGenerator, @@ -93,48 +94,15 @@ public function handle(): void { $this->prepareAppName(); - $kebabName = Str::kebab($this->appName); - - $this->codeOwnerEmail = $this->validateInput( - method: fn () => $this->ask('Please specify a Code Owner/Team Lead\'s email'), + $this->codeOwnerEmail = $this->askWithValidation( + parameter: 'Please specify a Code Owner/Team Lead\'s email', field: 'email of code owner / team lead', - rules: 'required|email', + rules: 'required|email' ); + + $this->appUrl = $this->ask('Please enter an application URL', "https://api.dev.{$this->kebabName}.com"); - $this->appUrl = $this->ask('Please enter an application URL', "https://api.dev.{$kebabName}.com"); - - $envFile = (file_exists('.env')) ? '.env' : '.env.example'; - - $envConfig = [ - 'APP_NAME' => $this->appName, - 'DB_CONNECTION' => $this->dbConnection, - 'DB_HOST' => $this->dbHost, - 'DB_PORT' => $this->dbPort, - 'DB_DATABASE' => $this->dbName, - 'DB_USERNAME' => $this->dbUserName, - 'DB_PASSWORD' => '', - ]; - - $this->updateEnvFile($envFile, $envConfig); - - if (!file_exists('.env.development')) { - copy('.env.example', '.env.development'); - } - - $this->updateEnvFile('.env.development', [ - 'APP_NAME' => $this->appName, - 'APP_URL' => $this->appUrl, - 'APP_MAINTENANCE_DRIVER' => 'cache', - 'CACHE_STORE' => 'redis', - 'QUEUE_CONNECTION' => 'redis', - 'SESSION_DRIVER' => 'redis', - 'DB_CONNECTION' => $this->dbConnection, - 'DB_HOST' => '', - 'DB_PORT' => '', - 'DB_DATABASE' => '', - 'DB_USERNAME' => '', - 'DB_PASSWORD' => '', - ]); + $this->updateEnvFile(); $this->info('Project initialized successfully!'); @@ -153,25 +121,7 @@ public function handle(): void )); if ($this->authType === AuthTypeEnum::Clerk) { - $this->enableClerk(); - - $data = [ - 'AUTH_GUARD' => 'clerk', - 'CLERK_ALLOWED_ISSUER' => '', - 'CLERK_SECRET_KEY' => '', - 'CLERK_SIGNER_KEY_PATH' => '', - ]; - - if ($this->appType !== AppTypeEnum::Mobile) { - $data['CLERK_ALLOWED_ORIGINS'] = ''; - } - - $this->updateEnvFile('.env.development', $data); - $this->updateEnvFile($envFile, $data); - - if ($envFile !== '.env.example') { - $this->updateEnvFile('.env.example', $data); - } + $this->configureClerk(); } if ($this->confirm('Do you want to generate an admin user?', true)) { @@ -179,48 +129,22 @@ public function handle(): void $this->publishAdminsTableMigration(); } - $this->createAdminUser($kebabName); + $this->createAdminUser(); } - if ($shouldGenerateReadme = $this->confirm('Do you want to generate a README file?', true)) { - $this->readmeGenerator->generate($this->appName, $this->appType->value, $this->appUrl); - - if ($this->confirm('Do you need a `Resources & Contacts` part?', true)) { - $this->readmeGenerator->fillResourcesAndContacts(); - $this->fillResources(); - $this->fillContacts(); - } - - if ($this->confirm('Do you need a `Prerequisites` part?', true)) { - $this->readmeGenerator->fillPrerequisites(); - } - - if ($this->confirm('Do you need a `Getting Started` part?', true)) { - $this->fillGettingStarted(); - } - - if ($this->confirm('Do you need an `Environments` part?', true)) { - $this->readmeGenerator->fillEnvironments(); - } - - if ($this->confirm('Do you need a `Credentials and Access` part?', true)) { - $this->fillCredentialsAndAccess($kebabName); - - if ($this->authType === AuthTypeEnum::Clerk) { - $this->readmeGenerator->fillClerkAuth(); - } - } + if ($this->shouldGenerateReadme = $this->confirm('Do you want to generate a README file?', true)) { + $this->generateReadme(); } if ($this->confirm('Would you use Renovate dependabot?', true)) { $this->saveRenovateJSON(); - if ($shouldGenerateReadme) { + if ($this->shouldGenerateReadme) { $this->readmeGenerator->fillRenovate(); } } - if ($shouldGenerateReadme) { + if ($this->shouldGenerateReadme) { $this->readmeGenerator->save(); $this->info('README generated successfully!'); @@ -269,6 +193,207 @@ public function handle(): void $this->runMigrations(); } + protected function askWithValidation(string $parameter, string $field, string|array $rules, ?string $default = null): string + { + $value = $default + ? $this->ask($parameter, $default) + : $this->ask($parameter); + + $validator = Validator::make([$field => $value], [$field => $rules]); + + if ($validator->fails()) { + $this->warn($validator->errors()->first()); + + $value = $this->askWithValidation($parameter, $field,$rules, $default); + } + + return $value; + } + + protected function prepareAppName(): void + { + $appName = $this->argument('application-name'); + + $pascalCaseAppName = ucfirst(Str::camel($appName)); + + if ($appName !== $pascalCaseAppName && $this->confirm("The application name is not in PascalCase, would you like to use {$pascalCaseAppName}", true)) { + $appName = $pascalCaseAppName; + } + + $this->appName = $appName; + + $this->kebabName = Str::kebab($this->appName); + } + + protected function updateEnvFile(): void + { + $this->envFile = (file_exists('.env')) ? '.env' : '.env.example'; + + $envConfig = [ + 'APP_NAME' => $this->appName, + 'DB_CONNECTION' => $this->envConfig['dbConnection'], + 'DB_HOST' => $this->envConfig['dbHost'], + 'DB_PORT' => $this->envConfig['dbPort'], + 'DB_DATABASE' => $this->envConfig['dbName'], + 'DB_USERNAME' => $this->envConfig['dbUserName'], + 'DB_PASSWORD' => '', + ]; + + $this->writeEnvFile($this->envFile, $envConfig); + + if (!file_exists('.env.development')) { + copy('.env.example', '.env.development'); + } + + $this->writeEnvFile('.env.development', [ + 'APP_NAME' => $this->appName, + 'APP_URL' => $this->appUrl, + 'APP_MAINTENANCE_DRIVER' => 'cache', + 'CACHE_STORE' => 'redis', + 'QUEUE_CONNECTION' => 'redis', + 'SESSION_DRIVER' => 'redis', + 'DB_CONNECTION' => $this->envConfig['dbConnection'], + 'DB_HOST' => '', + 'DB_PORT' => '', + 'DB_DATABASE' => '', + 'DB_USERNAME' => '', + 'DB_PASSWORD' => '', + ]); + } + + protected function configureClerk(): void + { + $this->enableClerk(); + + $data = [ + 'AUTH_GUARD' => 'clerk', + 'CLERK_ALLOWED_ISSUER' => '', + 'CLERK_SECRET_KEY' => '', + 'CLERK_SIGNER_KEY_PATH' => '', + ]; + + if ($this->appType !== AppTypeEnum::Mobile) { + $data['CLERK_ALLOWED_ORIGINS'] = ''; + } + + $this->writeEnvFile('.env.development', $data); + $this->writeEnvFile($this->envFile, $data); + + if ($this->envFile !== '.env.example') { + $this->writeEnvFile('.env.example', $data); + } + } + + protected function writeEnvFile(string $fileName, array $data): void + { + $env = EnvFile::open($fileName); + + $env->addEmptyLine(); + + $env->set($data); + + $env->write(); + } + + protected function enableClerk(): void + { + array_push( + $this->shellCommands, + 'composer require ronasit/laravel-clerk', + 'php artisan laravel-clerk:install', + ); + + $this->publishMigration( + view: view('initializator::users_add_clerk_id_field'), + migrationName: 'users_add_clerk_id_field', + ); + + $this->publishClass( + template: view('initializator::clerk_user_repository'), + fileName: 'ClerkUserRepository', + filePath: 'app/Support/Clerk', + ); + } + + protected function createAdminUser(string $serviceKey = '', string $serviceName = ''): array + { + $adminEmail = when(empty($serviceKey), "admin@{$this->kebabName}.com", "admin.{$serviceKey}@{$this->kebabName}.com"); + $defaultPassword = substr(md5(uniqid()), 0, 8); + + $serviceLabel = when(!empty($serviceName), " for {$serviceName}"); + + $adminCredentials = [ + 'email' => $this->ask("Please enter admin email{$serviceLabel}", $adminEmail), + 'password' => $this->ask("Please enter admin password{$serviceLabel}", $defaultPassword), + ]; + + if ($this->authType === AuthTypeEnum::None) { + $adminCredentials['name'] = $this->ask("Please enter admin name{$serviceLabel}", "{$serviceName} Admin"); + $adminCredentials['role_id'] = $this->ask("Please enter admin role id{$serviceLabel}", RoleEnum::Admin->value); + } + + if (empty($serviceName)) { + $this->adminCredentials = $adminCredentials; + } + + $this->publishAdminMigration($adminCredentials, $serviceKey); + + return $adminCredentials; + } + + protected function publishMigration(View $view, string $migrationName): void + { + $time = Carbon::now()->format('Y_m_d_His'); + + $migrationName = "{$time}_{$migrationName}"; + + $this->publishClass($view, $migrationName, 'database/migrations'); + } + + protected function publishClass(View $template, string $fileName, string $filePath): void + { + $fileName = "{$fileName}.php"; + + if (!is_dir($filePath)) { + mkdir($filePath, 0777, true); + } + + $data = $template->render(); + + file_put_contents("{$filePath}/{$fileName}", "readmeGenerator->generate($this->appName, $this->appType->value, $this->appUrl); + + if ($this->confirm('Do you need a `Resources & Contacts` part?', true)) { + $this->readmeGenerator->fillResourcesAndContacts(); + $this->fillResources(); + $this->fillContacts(); + } + + if ($this->confirm('Do you need a `Prerequisites` part?', true)) { + $this->readmeGenerator->fillPrerequisites(); + } + + if ($this->confirm('Do you need a `Getting Started` part?', true)) { + $this->fillGettingStarted(); + } + + if ($this->confirm('Do you need an `Environments` part?', true)) { + $this->readmeGenerator->fillEnvironments(); + } + + if ($this->confirm('Do you need a `Credentials and Access` part?', true)) { + $this->fillCredentialsAndAccess(); + + if ($this->authType === AuthTypeEnum::Clerk) { + $this->readmeGenerator->fillClerkAuth(); + } + } + } + protected function fillResources(): void { $filePart = $this->readmeGenerator->loadReadmePart('RESOURCES.md'); @@ -334,7 +459,7 @@ protected function fillGettingStarted(): void $this->readmeGenerator->updateReadmeFile($filePart); } - protected function fillCredentialsAndAccess(string $kebabName): void + protected function fillCredentialsAndAccess(): void { $filePart = $this->readmeGenerator->loadReadmePart('CREDENTIALS_AND_ACCESS.md'); @@ -359,7 +484,7 @@ protected function fillCredentialsAndAccess(string $kebabName): void $this->publishAdminsTableMigration(); } - $adminCredentials = $this->createAdminUser($kebabName, $key, $title); + $adminCredentials = $this->createAdminUser($key, $title); } $this->readmeGenerator->setReadmeValue($filePart, "{$key}_email", $adminCredentials['email']); @@ -370,6 +495,25 @@ protected function fillCredentialsAndAccess(string $kebabName): void $this->readmeGenerator->updateReadmeFile($filePart); } + protected function saveRenovateJSON(): void + { + $reviewer = $this->askWithValidation( + parameter: 'Please type username of the project reviewer', + field: 'username of the project reviewer', + rules: 'required|alpha_dash', + default: Str::before($this->codeOwnerEmail, '@') + ); + + $data = [ + '$schema' => 'https://docs.renovatebot.com/renovate-schema.json', + 'extends' => ['config:recommended'], + 'enabledManagers' => ['composer'], + 'assignees' => [$reviewer], + ]; + + file_put_contents('renovate.json', json_encode($data, JSON_PRETTY_PRINT)); + } + protected function setupComposerHooks(): void { $path = base_path('composer.json'); @@ -399,153 +543,26 @@ protected function addArrayItemIfMissing(array &$data, string $path, string $val } } - protected function setAutoDocContactEmail(string $email): void + protected function changeMiddlewareForTelescopeAuthorization(): void { - $config = ArrayFile::open(base_path('config/auto-doc.php')); - - $config->set('info.contact.email', $email); - - $config->write(); - } + $config = ArrayFile::open(base_path('config/telescope.php')); - protected function runMigrations(): void - { - config([ - 'database.default' => $this->dbConnection, - 'database.connections.pgsql' => [ - 'driver' => $this->dbConnection, - 'host' => $this->dbHost, - 'port' => $this->dbPort, - 'database' => $this->dbName, - 'username' => $this->dbUserName, - 'password' => '', - ], + // TODO: add Authorize::class middleware after inplementing an ability to modify functions in the https://github.com/RonasIT/larabuilder package + $config->set('middleware', [ + 'web', + 'auth:web', ]); - shell_exec('php artisan migrate --ansi --force'); - } - - protected function createAdminUser(string $kebabName, string $serviceKey = '', string $serviceName = ''): array - { - $adminEmail = when(empty($serviceKey), "admin@{$kebabName}.com", "admin.{$serviceKey}@{$kebabName}.com"); - $defaultPassword = substr(md5(uniqid()), 0, 8); - - $serviceLabel = when(!empty($serviceName), " for {$serviceName}"); - - $adminCredentials = [ - 'email' => $this->ask("Please enter admin email{$serviceLabel}", $adminEmail), - 'password' => $this->ask("Please enter admin password{$serviceLabel}", $defaultPassword), - ]; - - if ($this->authType === AuthTypeEnum::None) { - $adminCredentials['name'] = $this->ask("Please enter admin name{$serviceLabel}", "{$serviceName} Admin"); - $adminCredentials['role_id'] = $this->ask("Please enter admin role id{$serviceLabel}", RoleEnum::Admin->value); - } - - if (empty($serviceName)) { - $this->adminCredentials = $adminCredentials; - } - - $this->publishAdminMigration($adminCredentials, $serviceKey); - - return $adminCredentials; - } - - protected function publishClass(View $template, string $fileName, string $filePath): void - { - $fileName = "{$fileName}.php"; - - if (!is_dir($filePath)) { - mkdir($filePath, 0777, true); - } - - $data = $template->render(); - - file_put_contents("{$filePath}/{$fileName}", "format('Y_m_d_His'); - - $migrationName = "{$time}_{$migrationName}"; - - $this->publishClass($view, $migrationName, 'database/migrations'); - } - - protected function updateEnvFile(string $fileName, array $data): void - { - $env = EnvFile::open($fileName); - - $env->addEmptyLine(); - - $env->set($data); - - $env->write(); - } - - protected function prepareAppName(): void - { - $this->appName = $this->argument('application-name'); - - $pascalCaseAppName = ucfirst(Str::camel($this->appName)); - - if ($this->appName !== $pascalCaseAppName && $this->confirm("The application name is not in PascalCase, would you like to use {$pascalCaseAppName}", true)) { - $this->appName = $pascalCaseAppName; - } - } - - protected function saveRenovateJSON(): void - { - $reviewer = $this->validateInput( - method: fn () => $this->ask('Please type username of the project reviewer', Str::before($this->codeOwnerEmail, '@')), - field: 'username of the project reviewer', - rules: 'required|alpha_dash', - ); - - $data = [ - '$schema' => 'https://docs.renovatebot.com/renovate-schema.json', - 'extends' => ['config:recommended'], - 'enabledManagers' => ['composer'], - 'assignees' => [$reviewer], - ]; - - file_put_contents('renovate.json', json_encode($data, JSON_PRETTY_PRINT)); - } - - protected function validateInput(callable $method, string $field, string|array $rules): string - { - $value = $method(); - - $validator = Validator::make([$field => $value], [$field => $rules]); - - if ($validator->fails()) { - $this->warn($validator->errors()->first()); - - $value = $this->validateInput($method, $field, $rules); - } - - return $value; + $config->write(); } - protected function enableClerk(): void + protected function setAutoDocContactEmail(string $email): void { - array_push( - $this->shellCommands, - 'composer require ronasit/laravel-clerk', - 'php artisan laravel-clerk:install', - ); + $config = ArrayFile::open(base_path('config/auto-doc.php')); - $this->publishMigration( - view: view('initializator::users_add_clerk_id_field'), - migrationName: 'users_add_clerk_id_field', - ); + $config->set('info.contact.email', $email); - $this->publishClass( - template: view('initializator::clerk_user_repository'), - fileName: 'ClerkUserRepository', - filePath: 'app/Support/Clerk', - ); + $config->write(); } protected function publishWebLogin(): void @@ -555,17 +572,21 @@ protected function publishWebLogin(): void file_put_contents(base_path('routes/web.php'), "\nAuth::routes();\n", FILE_APPEND); } - protected function changeMiddlewareForTelescopeAuthorization(): void + protected function runMigrations(): void { - $config = ArrayFile::open(base_path('config/telescope.php')); - - // TODO: add Authorize::class middleware after inplementing an ability to modify functions in the https://github.com/RonasIT/larabuilder package - $config->set('middleware', [ - 'web', - 'auth:web', + config([ + 'database.default' => $this->envConfig['dbConnection'], + 'database.connections.pgsql' => [ + 'driver' => $this->envConfig['dbConnection'], + 'host' => $this->envConfig['dbHost'], + 'port' => $this->envConfig['dbPort'], + 'database' => $this->envConfig['dbName'], + 'username' => $this->envConfig['dbUserName'], + 'password' => '', + ], ]); - $config->write(); + shell_exec('php artisan migrate --ansi --force'); } protected function publishAdminMigration(array $adminCredentials, ?string $serviceKey): void