generated from yardinternet/skeleton-package
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUserRoles.php
97 lines (83 loc) · 2.76 KB
/
UserRoles.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
declare(strict_types=1);
namespace Yard\UserRoles;
use Illuminate\Contracts\Foundation\Application;
use Webmozart\Assert\Assert;
class UserRoles
{
/**
* Create a new UserRoles instance.
*/
public function __construct(protected Application $app)
{
}
public function setRoles(): void
{
if (is_multisite()) {
foreach (get_sites(['fields' => 'ids']) as $siteId) {
switch_to_blog($siteId);
$this->setRolesForSite();
}
} else {
$this->setRolesForSite();
}
}
private function setRolesForSite(): void
{
$prefix = config('user-roles.prefix');
Assert::stringNotEmpty($prefix);
$this->removeCurrentCustomRoles();
$this->addCustomRoles();
}
private function removeCurrentCustomRoles(): void
{
$prefix = config('user-roles.prefix');
$currentCustomRoles = \wp_roles()->roles;
$currentCustomRoles = array_filter(
array_keys($currentCustomRoles),
fn (string $role): bool => str_starts_with($role, $prefix)
);
foreach($currentCustomRoles as $role) {
remove_role($role);
}
}
private function addCustomRoles(): void
{
$prefix = config('user-roles.prefix');
$roles = config('user-roles.roles');
Assert::isArray($roles);
foreach($roles as $role => $properties) {
$capabilities = [];
if (! empty($properties['cap_groups'])) {
$capGroups = config('user-roles.cap_groups');
Assert::isArray($capGroups);
Assert::isArray($properties['cap_groups']);
foreach ($properties['cap_groups'] as $group) {
$groupCaps = $capGroups[$group];
Assert::isArray($groupCaps);
foreach ($groupCaps as $cap) {
$capabilities[$cap] = true;
}
}
}
if (! empty($properties['post_type_caps'])) {
Assert::isArray($properties['post_type_caps']);
foreach ($properties['post_type_caps'] as $postType) {
$postTypeCaps = get_post_type_object($postType)?->cap;
Assert::object($postTypeCaps);
foreach(array_values((array)$postTypeCaps) as $cap) {
$capabilities[$cap] = true;
}
}
}
foreach($properties['caps'] as $cap) {
$capabilities[$cap] = true;
}
add_role(
$prefix . '_' . $role,
$properties['display_name'],
$capabilities
);
}
}
}