1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Modules\User\Services; |
4
|
|
|
|
5
|
|
|
use Modules\User\Contracts\Authentication; |
6
|
|
|
use Modules\User\Events\UserHasRegistered; |
7
|
|
|
use Modules\User\Repositories\RoleRepository; |
8
|
|
|
|
9
|
|
|
class UserRegistration |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var Authentication |
13
|
|
|
*/ |
14
|
|
|
private $auth; |
15
|
|
|
/** |
16
|
|
|
* @var RoleRepository |
17
|
|
|
*/ |
18
|
|
|
private $role; |
19
|
|
|
/** |
20
|
|
|
* @var array |
21
|
|
|
*/ |
22
|
|
|
private $input; |
23
|
|
|
|
24
|
|
|
public function __construct(Authentication $auth, RoleRepository $role) |
25
|
|
|
{ |
26
|
|
|
$this->auth = $auth; |
27
|
|
|
$this->role = $role; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param array $input |
32
|
|
|
* @return mixed |
33
|
|
|
*/ |
34
|
|
|
public function register(array $input) |
35
|
|
|
{ |
36
|
|
|
$this->input = $input; |
37
|
|
|
|
38
|
|
|
$user = $this->createUser(); |
39
|
|
|
|
40
|
|
|
if ($this->hasProfileData()) { |
41
|
|
|
$this->createProfileForUser($user); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$this->assignUserToUsersGroup($user); |
45
|
|
|
|
46
|
|
|
event(new UserHasRegistered($user)); |
47
|
|
|
|
48
|
|
|
return $user; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
private function createUser() |
52
|
|
|
{ |
53
|
|
|
return $this->auth->register((array) $this->input); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
private function assignUserToUsersGroup($user) |
57
|
|
|
{ |
58
|
|
|
$role = $this->role->findByName($this->getDefaultRole()); |
59
|
|
|
|
60
|
|
|
$this->auth->assignRole($user, $role); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Check if the request input has a profile key |
65
|
|
|
* @return bool |
66
|
|
|
*/ |
67
|
|
|
private function hasProfileData() |
68
|
|
|
{ |
69
|
|
|
return isset($this->input['profile']); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Create a profile for the given user |
74
|
|
|
* @param $user |
75
|
|
|
*/ |
76
|
|
|
private function createProfileForUser($user) |
77
|
|
|
{ |
78
|
|
|
$profileData = array_merge($this->input['profile'], ['user_id' => $user->id]); |
79
|
|
|
app('Modules\Profile\Repositories\ProfileRepository')->create($profileData); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* @return string |
84
|
|
|
*/ |
85
|
|
|
private function getDefaultRole() |
86
|
|
|
{ |
87
|
|
|
$defaultRole = config('asgard.user.config.default_role'); |
88
|
|
|
|
89
|
|
|
return $defaultRole !== null ? $defaultRole : 'User'; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|