components->info("Creating a new backend 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(); $user = new User([ 'first_name' => $firstName, 'last_name' => $lastName, 'email' => $email, 'role' => $role, 'published' => true, 'published_at' => Carbon::now(), ]); $user->saveOrFail(); $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 \App\Enums\Users\RoleEnum */ private function askRole(): \App\Enums\Users\RoleEnum { $options = collect([ RoleEnum::conceptor, RoleEnum::admin, RoleEnum::visitor, ])->mapWithKeys(fn(RoleEnum $role) => [ Str::ucFirst($role->label()) => $role ]); /** @var string $choice */ $choice = $this->choice('Role', $options->keys()->all(), Str::ucFirst(RoleEnum::visitor->label())); return $options->get($choice); } }