86 lines
2.2 KiB
PHP
86 lines
2.2 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
namespace App\Console\Commands;
|
||
|
||
use App\Models\Role;
|
||
use App\Models\User;
|
||
use Illuminate\Console\Command;
|
||
use Illuminate\Support\Carbon;
|
||
use Illuminate\Support\Str;
|
||
use Illuminate\Support\Facades\Validator;
|
||
|
||
class UserCreate extends Command
|
||
{
|
||
/**
|
||
* The name and signature of the console command.
|
||
*
|
||
* @var string
|
||
*/
|
||
protected $signature = 'app:user-create';
|
||
|
||
/**
|
||
* The console command description.
|
||
*
|
||
* @var string
|
||
*/
|
||
protected $description = 'Создание нового пользователя';
|
||
|
||
/**
|
||
* Execute the console command.
|
||
*/
|
||
public function handle()
|
||
{
|
||
$username = $this->validateAsk('Введите имя пользователя', ['string|max:255']);
|
||
|
||
if ($this->confirm('Хотите создать пользователя со случайным паролем?')) {
|
||
$password = Str::random(8);
|
||
$this->info('Созданный пароль: ' . $password);
|
||
} else {
|
||
$password = $this->validateAsk('Введите пароль', ['string|min:8']);
|
||
}
|
||
|
||
$email = $this->validateAsk('Введите email', ['email']);
|
||
|
||
User::create([
|
||
'name' => $username,
|
||
'email' => $email,
|
||
'password' => bcrypt($password),
|
||
'email_verified_at' => Carbon::now(),
|
||
'role_uuid' => Role::where('code', 'user')->value('uuid'),
|
||
]);
|
||
|
||
$this->info('Пользователь создан!');
|
||
}
|
||
|
||
private function validateAsk(string $question, array $rules, bool $isSecret = false)
|
||
{
|
||
if ($isSecret) {
|
||
$value = $this->secret($question);
|
||
} else {
|
||
$value = $this->ask($question);
|
||
}
|
||
|
||
$validate = $this->validateInput($rules, $value);
|
||
|
||
if ($validate !== true) {
|
||
$this->error($validate);
|
||
$value = $this->validateAsk($question, $rules);
|
||
}
|
||
|
||
return $value;
|
||
}
|
||
|
||
private function validateInput($rules, $value)
|
||
{
|
||
$validator = Validator::make([key($rules) => $value], $rules);
|
||
|
||
if ($validator->fails()) {
|
||
return $validator->errors()->first(key($rules));
|
||
}
|
||
|
||
return true;
|
||
}
|
||
}
|