askString('What is the firstname?', 'Equipe'); $lastname = $this->askString('What is the lastname?', 'Web'); $email = $this->askEmail('What is the email?', 'equipe.web@ldc.fr'); $pwd = $this->askPassword('What is the password?'); $role = $this->askRole(); $user = new User(); $user->firstname = $firstname; $user->lastname = $lastname; $user->email = $email; $user->password = Hash::make($pwd); $user->email_verified_at = now(); $user->role = $role; $user->save(); $this->info('User created.'); return self::SUCCESS; } private function askString( string $wants, ?string $default ): string { $response = $this->ask($wants, $default); $response = is_string($response) ? $response : ''; $strlen = mb_strlen(trim($response)); if ($strlen >= 3 && $strlen <= 255) { return $response; } $this->warn('Answer has to be between 3 and 255 chars'); return $this->askString($wants, $default); } private function askEmail( string $wants, ?string $default ): string { $response = $this->ask($wants, $default); $response = is_string($response) ? $response : ''; $validator = Validator::make([ 'email' => $response, ], [ 'email' => ['required', 'email:rfc,strict,spoof', 'unique:users,email'], ]); if ($validator->passes()) { return $response; } $this->warn($validator->messages()->first('email')); return $this->askEmail($wants, $default); } private function askPassword( string $wants ): string { $response = $this->secret($wants); $responseConfirmed = $this->secret("Confirm : {$wants}"); $response = is_string($response) ? $response : ''; $responseConfirmed = is_string($responseConfirmed) ? $responseConfirmed : ''; $validator = Validator::make([ 'password' => $response, 'password_confirmation' => $responseConfirmed, ], [ 'password' => ['required', 'confirmed', Password::min(8)->letters()->mixedCase()->numbers()->symbols()], ]); if ($validator->passes()) { return $response; } $this->warn($validator->messages()->first('password')); return $this->askPassword($wants); } private function askRole(): UserRole { $role = null; $possibles = collect(UserRole::cases()) ->map(fn ($role) => $this->roleToString($role)) ->all(); $response = Arr::wrap( $this->choice( question: 'What is the role ?', choices: $possibles, default: $this->roleToString(UserRole::Admin), multiple: false ) ); $role = UserRole::tryFrom( intval(mb_strcut((string) $response[0], 0, 1)) ); if (! is_null($role)) { return $role; } $this->warn('Need a valid role, try again'); return $this->askRole(); } private function roleToString(UserRole $role): string { return "{$role->value()} : {$role->label()}"; } }