1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Containers\Authorization\Tasks; |
4
|
|
|
|
5
|
|
|
use App\Containers\Authorization\Data\Repositories\RoleRepository; |
6
|
|
|
use App\Containers\User\Models\User; |
7
|
|
|
use App\Containers\User\Tasks\FindUserByIdTask; |
8
|
|
|
use App\Port\Task\Abstracts\Task; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class AssignUserToRoleTask. |
12
|
|
|
* |
13
|
|
|
* @author Mahmoud Zalt <[email protected]> |
14
|
|
|
*/ |
15
|
|
View Code Duplication |
class AssignUserToRoleTask extends Task |
|
|
|
|
16
|
|
|
{ |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var \App\Containers\Authorization\Data\Repositories\RoleRepository |
20
|
|
|
*/ |
21
|
|
|
private $roleRepository; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var \App\Containers\User\Tasks\FindUserByIdTask |
25
|
|
|
*/ |
26
|
|
|
private $findUserByIdTask; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* AssignUserToRoleTask constructor. |
30
|
|
|
* |
31
|
|
|
* @param \App\Containers\Authorization\Data\Repositories\RoleRepository $roleRepository |
32
|
|
|
* @param \App\Containers\User\Tasks\FindUserByIdTask $findUserByIdTask |
33
|
|
|
*/ |
34
|
|
|
public function __construct(RoleRepository $roleRepository, FindUserByIdTask $findUserByIdTask) |
35
|
|
|
{ |
36
|
|
|
$this->roleRepository = $roleRepository; |
37
|
|
|
$this->findUserByIdTask = $findUserByIdTask; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param \App\Containers\User\Models\User $user | $userId |
42
|
|
|
* @param $roles |
43
|
|
|
* |
44
|
|
|
* @return \App\Containers\User\Models\User |
45
|
|
|
*/ |
46
|
|
|
public function run($user, $roles) |
47
|
|
|
{ |
48
|
|
|
if (!$user instanceof User) { |
49
|
|
|
$user = $this->findUserByIdTask->run($user); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if (is_array($roles)) { |
53
|
|
|
foreach ($roles as $role) { |
54
|
|
|
$this->assignRole($user, $role); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
} else { |
58
|
|
|
$this->assignRole($user, $roles); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
return $user; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @param $user |
66
|
|
|
* @param $role |
67
|
|
|
* |
68
|
|
|
* @return mixed |
69
|
|
|
*/ |
70
|
|
|
private function assignRole($user, $role) |
71
|
|
|
{ |
72
|
|
|
$user = $user->assignRole($this->roleRepository->findWhere(['name' => $role])->first()); |
73
|
|
|
|
74
|
|
|
return $user; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
} |
78
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.