|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Console\Commands; |
| 4 | + |
| 5 | +use App\Models\Role; |
| 6 | +use App\Models\User; |
| 7 | +use Illuminate\Console\Command; |
| 8 | +use Illuminate\Support\Facades\DB; |
| 9 | +use Illuminate\Support\Facades\Hash; |
| 10 | +use Throwable; |
| 11 | + |
| 12 | +class RegisterUser extends Command |
| 13 | +{ |
| 14 | + /** |
| 15 | + * The name and signature of the console command. |
| 16 | + * |
| 17 | + * @var string |
| 18 | + */ |
| 19 | + protected $signature = 'user:register {name} {email} {password} {role}'; |
| 20 | + |
| 21 | + /** |
| 22 | + * The console command description. |
| 23 | + * |
| 24 | + * @var string |
| 25 | + */ |
| 26 | + protected $description = 'Register a new user in format: Name.Surname, name@example.com, password, role=admin,editor,user'; |
| 27 | + |
| 28 | + /** |
| 29 | + * Execute the console command. |
| 30 | + */ |
| 31 | + public function handle(): void |
| 32 | + { |
| 33 | + $name = $this->argument('name'); |
| 34 | + $email = $this->argument('email'); |
| 35 | + $password = $this->argument('password'); |
| 36 | + $role = $this->argument('role'); |
| 37 | + |
| 38 | + if (!in_array($role, ['admin', 'editor', 'user'])) { |
| 39 | + $this->error('Invalid role. Allowed roles: admin,editor,user'); |
| 40 | + return; |
| 41 | + } |
| 42 | + |
| 43 | + if (!str_contains($name, '.')) { |
| 44 | + $this->error('Invalid name format. Allowed format: Name.Surname'); |
| 45 | + return; |
| 46 | + } |
| 47 | + |
| 48 | + if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { |
| 49 | + $this->error('Invalid email format.'); |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + DB::beginTransaction(); |
| 54 | + try { |
| 55 | + $user = User::query() |
| 56 | + ->create([ |
| 57 | + 'name' => str_replace('.', ' ', $name), |
| 58 | + 'email' => $email, |
| 59 | + 'password' => Hash::make($password), |
| 60 | + 'email_verified_at' => now(), |
| 61 | + ]); |
| 62 | + |
| 63 | + $userRole = Role::query() |
| 64 | + ->where('name', $role) |
| 65 | + ->first(); |
| 66 | + |
| 67 | + $user->roles()->attach($userRole); |
| 68 | + |
| 69 | + DB::commit(); |
| 70 | + |
| 71 | + $this->info('User registered successfully.'); |
| 72 | + |
| 73 | + } catch (Throwable $th) { |
| 74 | + DB::rollBack(); |
| 75 | + $this->error($th->getMessage()); |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments