112 lines
3.4 KiB
PHP
112 lines
3.4 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\ValidationException;
|
|
use Kwaadpepper\Enum\Rules\EnumIsValidRule;
|
|
|
|
class CreateAdmin extends Command
|
|
{
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'create:admin';
|
|
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = 'Create an admin user';
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*
|
|
* @return integer
|
|
*/
|
|
public function handle()
|
|
{
|
|
$name = null;
|
|
while (is_null($name)) {
|
|
try {
|
|
$tmp = $this->ask('What is the name?', 'Equipe Web');
|
|
$validator = Validator::make(['name' => $tmp], [
|
|
'name' => 'required|min:5,max:255'
|
|
]);
|
|
$validator->validate();
|
|
$name = $tmp;
|
|
} catch (ValidationException $e) {
|
|
$this->error(sprintf(
|
|
'Please provide a valid name %s',
|
|
\implode(',', collect($e->errors())->flatten()->all())
|
|
));
|
|
continue;
|
|
}
|
|
}
|
|
|
|
$email = null;
|
|
while (is_null($email)) {
|
|
try {
|
|
$tmp = $this->ask('What is the email?', 'equipe.web@ldc.fr');
|
|
$validator = Validator::make(['email' => $tmp], [
|
|
'email' => 'required|unique:users,email|email:rfc,dns'
|
|
]);
|
|
$validator->validate();
|
|
$email = $tmp;
|
|
} catch (ValidationException $e) {
|
|
$this->error(sprintf(
|
|
'Please provide a valid email %s',
|
|
\implode(',', collect($e->errors())->flatten()->all())
|
|
));
|
|
continue;
|
|
}
|
|
}
|
|
|
|
$role = null;
|
|
while (is_null($role)) {
|
|
try {
|
|
$tmp = $this->ask('Type the wanted user role', sprintf(
|
|
'%d (%s), %d (%s)',
|
|
UserRole::admin()->value,
|
|
UserRole::admin()->label,
|
|
UserRole::brand()->value,
|
|
UserRole::brand()->label
|
|
));
|
|
$validator = Validator::make(['role' => $tmp], [
|
|
'role' => [
|
|
'required', new EnumIsValidRule(UserRole::class),
|
|
sprintf('in:%d,%d', UserRole::admin()->value, UserRole::brand()->value)
|
|
]
|
|
]);
|
|
$validator->validate();
|
|
$role = $tmp;
|
|
} catch (ValidationException $e) {
|
|
$this->error(sprintf(
|
|
'Please provide a valid role %s',
|
|
\implode(',', collect($e->errors())->flatten()->all())
|
|
));
|
|
continue;
|
|
} //end try
|
|
} //end while
|
|
|
|
$password = $this->secret('What is the password?');
|
|
|
|
$user = new User();
|
|
$user->name = $name;
|
|
$user->email = $email;
|
|
$user->password = Hash::make($password);
|
|
$user->role = $role;
|
|
$user->saveOrFail();
|
|
|
|
$this->info('User created.');
|
|
|
|
return 0;
|
|
}
|
|
}
|