Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
14 / 14 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| AuthorizationDrupalRolesService | |
100.00% |
14 / 14 |
|
100.00% |
3 / 3 |
8 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| getRoles | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
| setRoles | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
4 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Drupal\authorization_drupal_roles\Service; |
| 6 | |
| 7 | use Drupal\authorization_drupal_roles\AuthorizationDrupalRolesInterface; |
| 8 | use Drupal\user\UserDataInterface; |
| 9 | |
| 10 | /** |
| 11 | * Class UserRoleService. |
| 12 | * |
| 13 | * @package Drupal\authorization_drupal_roles\Service |
| 14 | */ |
| 15 | class AuthorizationDrupalRolesService implements AuthorizationDrupalRolesInterface { |
| 16 | |
| 17 | /** |
| 18 | * User data. |
| 19 | * |
| 20 | * @var \Drupal\user\UserDataInterface |
| 21 | */ |
| 22 | protected $userData; |
| 23 | |
| 24 | /** |
| 25 | * The module for UserData. |
| 26 | * |
| 27 | * Override this in any child class to change its module. |
| 28 | * |
| 29 | * @var string |
| 30 | */ |
| 31 | protected $module = 'authorization_drupal_roles'; |
| 32 | |
| 33 | /** |
| 34 | * UserRoleService constructor. |
| 35 | * |
| 36 | * @param \Drupal\user\UserDataInterface $user_data |
| 37 | * User data. |
| 38 | */ |
| 39 | public function __construct(UserDataInterface $user_data) { |
| 40 | $this->userData = $user_data; |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * {@inheritdoc} |
| 45 | */ |
| 46 | public function getRoles($user_id, string $profile_id) { |
| 47 | $roles = []; |
| 48 | $role_data = $this->userData->get($this->module, $user_id, 'roles') ?? []; |
| 49 | foreach ($role_data as $role => $profile) { |
| 50 | if ($profile === $profile_id) { |
| 51 | $roles[] = $role; |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | return $roles; |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * {@inheritdoc} |
| 60 | */ |
| 61 | public function setRoles($user_id, string $profile_id, array $roles) { |
| 62 | $role_data = $this->userData->get($this->module, $user_id, 'roles') ?? []; |
| 63 | foreach ($role_data as $role => $profile) { |
| 64 | if ($profile === $profile_id) { |
| 65 | unset($role_data[$role]); |
| 66 | } |
| 67 | } |
| 68 | foreach ($roles as $role) { |
| 69 | $role_data[$role] = $profile_id; |
| 70 | } |
| 71 | |
| 72 | $this->userData->set($this->module, $user_id, 'roles', $role_data); |
| 73 | } |
| 74 | |
| 75 | } |