commit | author | age
|
9f6455
|
1 |
<?php |
DC |
2 |
|
|
3 |
namespace App\Console\Commands; |
|
4 |
|
|
5 |
use Illuminate\Console\Command; |
|
6 |
use Illuminate\Support\Facades\Hash; |
|
7 |
|
|
8 |
class CreateUserCommand extends Command |
|
9 |
{ |
|
10 |
public const E_OK = 0; |
|
11 |
public const E_USER_EXISTS = 1; |
|
12 |
public const E_UPDATING_FAILED = 2; |
|
13 |
public const E_CHAOS = 5; |
|
14 |
/** |
|
15 |
* The name and signature of the console command. |
|
16 |
* |
|
17 |
* @var string |
|
18 |
*/ |
|
19 |
protected $signature = 'user:create |
|
20 |
{username? : Select the new users name} |
|
21 |
{email? : Select the new users email} |
|
22 |
{password? : Select the new users password} |
|
23 |
{--force : Overwrite existing users }'; |
|
24 |
/** |
|
25 |
* The console command description. |
|
26 |
* |
|
27 |
* @var string |
|
28 |
*/ |
|
29 |
protected $description = 'Create a user with a command with artisan'; |
|
30 |
|
|
31 |
/** |
|
32 |
* Execute the console command. |
|
33 |
* |
|
34 |
* @return mixed |
|
35 |
*/ |
|
36 |
public function handle() |
|
37 |
{ |
|
38 |
$class = config( |
|
39 |
'auth.providers.' |
|
40 |
.config( |
|
41 |
'auth.guards.' |
|
42 |
.config('auth.defaults.guard', 'web') |
|
43 |
.'.provider' |
|
44 |
) |
|
45 |
.'.model' |
|
46 |
); |
|
47 |
|
|
48 |
$user = new $class(); |
|
49 |
|
|
50 |
$user->username = ($this->argument('username') === null) |
|
51 |
? $this->ask('User name: ') |
|
52 |
: $this->argument('username'); |
|
53 |
|
|
54 |
$user->email = ($this->argument('email') === null) |
|
55 |
? $this->ask('User email: ') |
|
56 |
: $this->argument('email'); |
|
57 |
|
|
58 |
$user->password = ($this->argument('password') === null) |
|
59 |
? Hash::make($this->ask('User password: ')) |
|
60 |
: Hash::make($this->argument('password')); |
|
61 |
|
|
62 |
if ($this->option('force') === true || $this->confirm('Save this user?', true)) { |
|
63 |
$exists = (new $class)->where([ |
|
64 |
'username' => $user->username, |
|
65 |
'email' => $user->email, |
|
66 |
])->first(); |
|
67 |
if ($exists === null) { // user is not exisiting yet, just create him and return |
|
68 |
$user->save(); |
|
69 |
$this->info('Created a user with id: '.$user->id); |
|
70 |
|
|
71 |
return self::E_OK; |
|
72 |
} |
|
73 |
// user is already existing, check the input and handle |
|
74 |
if ($this->option('force')) { |
|
75 |
if ($exists->update($user->getAttributes())) { |
|
76 |
$this->info('Updated an existing user with id: '.$exists->id); |
|
77 |
|
|
78 |
return self::E_OK; |
|
79 |
} |
|
80 |
$this->warn('Updating an existing user with id: '.$exists->id.' ended with errors'); |
|
81 |
|
|
82 |
return self::E_UPDATING_FAILED; |
|
83 |
} |
|
84 |
$this->error('User already exist with id: '.$exists->id); |
|
85 |
|
|
86 |
return self::E_USER_EXISTS; |
|
87 |
} |
|
88 |
|
|
89 |
return self::E_CHAOS; // default end with an error to show, that this line was hit accidentially |
|
90 |
} |
|
91 |
} |