components->info("Creating a new Support user..."); $firstName = $this->askValid( 'first_name', 'First name', 'Admin', ['required', 'min:3', 'max:255'], ); $lastName = $this->askValid( 'last_name', 'Last name', 'Saïtama', ['required', 'min:3', 'max:255'], ); $email = $this->askValid( 'email', 'Email', 'equipe.web@ldc.fr', ['required', 'unique:users,email', 'email:rfc,strict,dns,spoof,filter'], ); $role = $this->askRole(); $password = $this->askPassword(); $user = new User([ 'first_name' => $firstName, 'last_name' => $lastName, 'email' => $email, 'role' => $role->value, 'published' => true, 'published_at' => Date::now(), ]); $user->saveOrFail(); $user->userPassword()->create([ 'password' => bcrypt($password), ]); $this->components->success("User {$firstName} {$lastName} created successfully."); } /** * Ask for a value and validate it, re-prompting on failure. * * @param string $field * @param string $label * @param string $default * @param array $rules * @return string */ private function askValid(string $field, string $label, string $default, array $rules): string { try { $value = $this->ask(sprintf("Type the wanted user %s", $label), $default); $validator = Validator::make([$field => $value], [$field => $rules]); $validator->validate(); return $value; } catch (ValidationException $e) { $this->components->error( collect($e->errors())->flatten()->first() ); return $this->askValid($field, $label, $default, $rules); } } /** * Ask for a role and return the corresponding RoleEnum. * * @return object */ private function askRole(): object { $options = collect(UserRoleRegistry::all())->mapWithKeys(fn(object $role) => [ Str::ucFirst($role->label) => $role ]); $choice = $this->choice('Role', $options->keys()->all(), Str::ucFirst(UserRoleRegistry::get('client')->label)); $choiceKey = is_string($choice) ? $choice : (string) $choice[0]; return $options->get($choiceKey) ?? UserRoleRegistry::get('client'); } /** * Ask for a password and confirmation password. * * @return string */ private function askPassword(): string { $password = $this->secret('Type the wanted user Password'); $passwordConfirmation = $this->secret('Confirm the password'); try { Validator::make( [ 'password' => $password, 'password_confirmation' => $passwordConfirmation, ], [ 'password' => [ 'required', 'confirmed', 'max:255', Password::min(8)->letters()->mixedCase()->numbers()->symbols()->uncompromised(), ], ] )->validate(); return $password; } catch (ValidationException $e) { $this->components->error(collect($e->errors())->flatten()->first()); return $this->askPassword(); } } }