ldc-supportweb/app/Console/Commands/CreateUser.php
2023-08-14 09:23:39 +00:00

168 lines
3.9 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Enums\Users\RoleEnum;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
class CreateUser extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'user:create';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a user';
/**
* The name of the new user.
*
* @var string
*/
protected $name;
/**
* The email of the new user.
*
* @var string
*/
protected $email;
/**
* The password of the new user.
*
* @var string
*/
protected $password;
/**
* The role of the new user.
*
* @var integer
*/
protected $role;
/**
* Execute the console command.
*
* @return integer
*/
public function handle()
{
$this->name = null;
$this->addName();
$this->email = null;
$this->addEmail();
$this->password = null;
$this->addPassword();
$this->role = null;
$this->addRole();
$user = new User([
'name' => $this->name,
'email' => $this->email,
'password' => $this->password,
'role' => $this->role
]);
$user->saveOrFail();
$this->info('User created.');
return 0;
}
/**
* Add a firstname to the user.
*
* @return void
*/
private function addName(): void
{
while (is_null($this->name)) {
try {
$tmp = $this->ask('Type the wanted user name', 'Admin');
$validator = Validator::make(['name' => $tmp], [
'name' => 'required|min:3|max:255'
]);
$validator->validate();
$this->name = $tmp;
} catch (ValidationException $e) {
$this->error(sprintf(
'Please provide a valid name %s',
\implode(',', collect($e->errors())->flatten()->all())
));
continue;
} //end try
}; //end while
}
/**
* Add an email to the user.
*
* @return void
*/
private function addEmail(): void
{
while (is_null($this->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();
$this->email = $tmp;
} catch (ValidationException $e) {
$this->error(sprintf(
'Please provide a valid email %s',
\implode(',', collect($e->errors())->flatten()->all())
));
continue;
} //end try
}; //end while
}
/**
* Add a password to the user.
*
* @return void
*/
private function addPassword(): void
{
while (
($this->password = $this->secret(
(!\is_null($this->password) ? 'Failed to confirm, ' : '') . 'Type the wanted user password'
)) !== $this->secret('Confirm the password')
) {
continue;
}; //end while
}
/**
* Add a password to the user.
*
* @return void
*/
private function addRole(): void
{
while (is_null($this->role)) {
$tmp = $this->confirm('Is the user an admin?');
$validator = Validator::make(['role' => $tmp], [
'role' => 'required|boolean'
]);
$validator->validate();
$this->role = $tmp ? RoleEnum::admin : RoleEnum::client;
};
}
}