95 lines
3.1 KiB
PHP
95 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Enums\UserRole;
|
|
use App\Models\User;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Validation\Rule;
|
|
use Illuminate\Validation\Rules\Password;
|
|
|
|
class CreateUser extends Command
|
|
{
|
|
protected $signature = 'user:create
|
|
{--name= : The unique user name}
|
|
{--email= : The unique email address}
|
|
{--role= : The user role: user, admin, or moderator}
|
|
{--locale=fr : The user locale}
|
|
{--verified : Mark the email address as verified}';
|
|
|
|
protected $description = 'Create an application user.';
|
|
|
|
public function handle(): int
|
|
{
|
|
$name = trim((string) ($this->option('name') ?: $this->ask('Name')));
|
|
$email = strtolower(trim((string) ($this->option('email') ?: $this->ask('Email address'))));
|
|
$role = (string) ($this->option('role') ?: $this->choice(
|
|
'Role',
|
|
array_column(UserRole::cases(), 'value'),
|
|
UserRole::USER->value,
|
|
));
|
|
$locale = strtolower(trim((string) $this->option('locale')));
|
|
|
|
$attributesValidator = Validator::make([
|
|
'name' => $name,
|
|
'email' => $email,
|
|
'role' => $role,
|
|
'locale' => $locale,
|
|
], [
|
|
'name' => ['required', 'string', 'min:3', 'max:32', 'regex:/^[a-zA-Z0-9_.-]+$/', 'unique:users,name'],
|
|
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
|
|
'role' => ['required', Rule::enum(UserRole::class)],
|
|
'locale' => ['required', Rule::in(config('app.supported_locales', ['fr', 'en']))],
|
|
]);
|
|
|
|
if ($attributesValidator->fails()) {
|
|
foreach ($attributesValidator->errors()->all() as $error) {
|
|
$this->components->error($error);
|
|
}
|
|
|
|
return self::FAILURE;
|
|
}
|
|
|
|
$password = (string) $this->secret('Password');
|
|
$passwordConfirmation = (string) $this->secret('Confirm password');
|
|
|
|
$passwordValidator = Validator::make([
|
|
'password' => $password,
|
|
'password_confirmation' => $passwordConfirmation,
|
|
], [
|
|
'password' => [
|
|
'required',
|
|
'confirmed',
|
|
Password::min(8)
|
|
->mixedCase()
|
|
->letters()
|
|
->numbers()
|
|
->symbols(),
|
|
],
|
|
]);
|
|
|
|
if ($passwordValidator->fails()) {
|
|
foreach ($passwordValidator->errors()->all() as $error) {
|
|
$this->components->error($error);
|
|
}
|
|
|
|
return self::FAILURE;
|
|
}
|
|
|
|
$user = User::query()->create([
|
|
'name' => $name,
|
|
'email' => $email,
|
|
'email_verified_at' => $this->option('verified') ? now() : null,
|
|
'locale' => $locale,
|
|
'password' => Hash::make($password),
|
|
'role' => UserRole::from($role),
|
|
]);
|
|
|
|
$this->components->info("User {$user->email} created with ID {$user->getKey()} and role {$user->role->value}.");
|
|
|
|
return self::SUCCESS;
|
|
}
|
|
}
|