ldc-portsalaries/app/Console/Commands/UserCreate.php
2021-06-07 18:28:25 +02:00

118 lines
3.4 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Enums\Role;
use App\Models\Site;
use App\Models\User;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
/**
* Creates a new user
*/
class UserCreate 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 backend user';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$sitename = $this->ask('For which site would you like to create a user ?');
$site = Site::where('name', 'LIKE', "%$sitename%")->first();
if ($site) {
if (!$this->confirm(sprintf('Would you like to use %s ? ', $site->name))) {
$this->info('Command cancelled');
return 0;
}
} else {
$this->error(sprintf('Site %s not found cancelled', $sitename));
return 0;
}
$name = null;
while (is_null($name)) {
try {
$tmp = $this->ask('What is user the name?');
$validator = Validator::make(['nom' => $tmp], [
'nom' => '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?');
$validator = Validator::make(['email' => $tmp], [
'email' => 'required|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 {
$num = $this->ask(sprintf(
'What is the user role %s ?',
implode(',', collect(Role::toArray())->map(function ($role) {
return sprintf('(%s) %d', $role->label, $role->value);
})->all())
));
if (!\is_numeric($num)) {
$this->error('Please provide a valid role.');
continue;
}
$role = Role::make(intval($num))->value;
} catch (Exception $e) {
$this->error('Please provide a valid role.');
continue;
}
}
$password = $this->secret('What is the password?');
$user = new User([
'name' => $name,
'email' => $email,
'role' => $role,
'password' => $password,
'site_id' => $site->id
]);
$user->saveOrFail();
$this->info('User created.');
return 0;
}
}