Move permission match code from class `User` to `Role`

This commit is contained in:
Johannes Meyer 2021-01-22 15:47:36 +01:00
parent 57b4a31bc3
commit c0541d70e9
2 changed files with 39 additions and 21 deletions

View File

@ -106,4 +106,41 @@ class Role
$this->restrictions = $restrictions;
return $this;
}
/**
* Whether this role grants the given permission
*
* @param string $permission
*
* @return bool
*/
public function grants($permission)
{
$requiredWildcard = strpos($permission, '*');
foreach ($this->permissions as $grantedPermission) {
if ($grantedPermission === '*' || $grantedPermission === $permission) {
return true;
}
if ($requiredWildcard !== false) {
if (($grantedWildcard = strpos($grantedPermission, '*')) !== false) {
$wildcard = min($requiredWildcard, $grantedWildcard);
} else {
$wildcard = $requiredWildcard;
}
} else {
$wildcard = strpos($grantedPermission, '*');
}
if ($wildcard !== false && $wildcard > 0) {
if (substr($permission, 0, $wildcard) === substr($grantedPermission, 0, $wildcard)) {
return true;
}
} elseif ($permission === $grantedPermission) {
return true;
}
}
return false;
}
}

View File

@ -563,27 +563,8 @@ class User
*/
public function can($requiredPermission)
{
if (isset($this->permissions['*']) || isset($this->permissions[$requiredPermission])) {
return true;
}
$requiredWildcard = strpos($requiredPermission, '*');
foreach ($this->permissions as $grantedPermission) {
if ($requiredWildcard !== false) {
if (($grantedWildcard = strpos($grantedPermission, '*')) !== false) {
$wildcard = min($requiredWildcard, $grantedWildcard);
} else {
$wildcard = $requiredWildcard;
}
} else {
$wildcard = strpos($grantedPermission, '*');
}
if ($wildcard !== false && $wildcard > 0) {
if (substr($requiredPermission, 0, $wildcard) === substr($grantedPermission, 0, $wildcard)) {
return true;
}
} elseif ($requiredPermission === $grantedPermission) {
foreach ($this->getRoles() as $role) {
if ($role->grants($requiredPermission)) {
return true;
}
}