ldc-boutique-cnc/app/Console/Commands/CreateAdmin.php

103 lines
3.2 KiB
PHP
Raw Normal View History

2021-02-23 16:28:45 +01:00
<?php
namespace App\Console\Commands;
use App\Enums\UserRole;
2021-02-23 16:28:45 +01:00
use App\Models\User;
use Illuminate\Console\Command;
2022-09-30 15:11:52 +02:00
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
2021-02-23 16:28:45 +01:00
class CreateAdmin extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
2022-09-30 15:11:52 +02:00
protected $signature = 'user:create';
2021-02-23 16:28:45 +01:00
/**
* The console command description.
*
* @var string
*/
2022-09-30 15:11:52 +02:00
protected $description = 'Create a backend admin user';
2021-02-23 16:28:45 +01:00
/**
* Execute the console command.
*
2022-09-03 16:56:16 +02:00
* @return void
2021-02-23 16:28:45 +01:00
*/
public function handle()
{
2022-09-30 15:11:52 +02:00
$email = null;
while (is_null($email)) {
try {
$tmp = $this->ask('Type the wanted user 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;
}
}
$firstname = null;
while (is_null($firstname)) {
try {
$tmp = $this->ask('Type the wanted user firstname', 'Admin');
$validator = Validator::make(['firstname' => $tmp], [
'firstname' => 'required|min:5,max:255'
]);
$validator->validate();
$firstname = $tmp;
} catch (ValidationException $e) {
$this->error(sprintf(
'Please provide a valid firstname %s',
\implode(',', collect($e->errors())->flatten()->all())
));
continue;
}
}
$lastname = null;
while (is_null($lastname)) {
try {
$tmp = $this->ask('Type the wanted user lastname', 'Saïtama');
$validator = Validator::make(['lastname' => $tmp], [
'lastname' => 'required|min:5,max:255'
]);
$validator->validate();
$lastname = $tmp;
} catch (ValidationException $e) {
$this->error(sprintf(
'Please provide a valid lastname %s',
\implode(',', collect($e->errors())->flatten()->all())
));
continue;
}
}
$password = $this->secret('Type the wanted user password');
2022-08-25 12:26:43 +02:00
$user = new User();
$user->firstname = $firstname;
$user->lastname = $lastname;
$user->date_of_birth = now();
$user->email = $email;
2022-09-30 15:11:52 +02:00
$user->password = $password;
$user->role = $this->confirm('Is the user an admin?') ?
UserRole::admin() : UserRole::user();
2021-02-23 16:28:45 +01:00
$user->email_verified_at = now();
2022-09-30 15:11:52 +02:00
$user->saveOrFail();
2021-02-23 16:28:45 +01:00
$this->info('User created.');
}
}