| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Copyright Andreas Heigl <andreas@heigl.org> |
| 5 |
* |
| 6 |
* Licenses under the MIT-license. For details see the included file LICENSE.md |
| 7 |
*/ |
| 8 |
|
| 9 |
declare(strict_types=1); |
| 10 |
|
| 11 |
namespace Org_Heigl\AuthLdap; |
| 12 |
|
| 13 |
use WP_User; |
| 14 |
|
| 15 |
use function array_search; |
| 16 |
use function in_array; |
| 17 |
use function var_dump; |
| 18 |
|
| 19 |
class UserRoleHandler |
| 20 |
{ |
| 21 |
/** |
| 22 |
* @param WP_User $user |
| 23 |
* @param string[] $roles |
| 24 |
* @return void |
| 25 |
*/ |
| 26 |
public function addRolesToUser(WP_User $user, $roles): void |
| 27 |
{ |
| 28 |
if ($roles === []) { |
| 29 |
return; |
| 30 |
} |
| 31 |
|
| 32 |
if ($user->roles == $roles) { |
| 33 |
return; |
| 34 |
} |
| 35 |
|
| 36 |
// Remove unused roles from existing. |
| 37 |
foreach ($user->roles as $role) { |
| 38 |
if (!in_array($role, $roles)) { |
| 39 |
// Remove unused roles. |
| 40 |
$user->remove_role($role); |
| 41 |
continue; |
| 42 |
} |
| 43 |
// Remove the existing role from roles. |
| 44 |
if (($key = array_search($role, $roles)) !== false) { |
| 45 |
unset($roles[$key]); |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
// Add new ones if not already assigned. |
| 50 |
foreach ($roles as $role) { |
| 51 |
$user->add_role($role); |
| 52 |
} |
| 53 |
} |
| 54 |
} |
| 55 |
|