Files
ignacionelson 6e47d76ba6 ProjectSend 2.0.0
Client file sharing, rebuilt from the ground up: a private area per
client, resumable uploads, folders, groups and categories, sharing with
expiry dates and download limits, comments, file versions, an activity
log, a REST API, and sixteen languages.

This repository begins here. ProjectSend 2 was developed privately, and
that development history is not published — the previous generation
remains available, with its own history, at projectsend/legacy.

Free software under the GNU General Public License v2, or (at your
option) any later version.
2026-08-14 01:38:12 -03:00

69 lines
1.7 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Modules\Identity\Permissions;
use App\Models\User;
use App\Modules\Identity\Models\Role;
use App\Modules\Identity\Models\RolePermission;
class PermissionChecker
{
/**
* Granted permission keys per role id, loaded once per request.
*
* @var array<int, array<string, bool>>
*/
private array $granted = [];
public function allows(User $user, Permission $permission): bool
{
$role = $user->role;
if ($role === null) {
return false;
}
if ($role->is_administrator) {
return true;
}
return isset($this->grantedFor($role)[$permission->value]);
}
/**
* Every permission key granted to the user, for UI hiding.
*
* @return list<string>
*/
public function grantedKeys(User $user): array
{
$role = $user->role;
if ($role === null) {
return [];
}
if ($role->is_administrator) {
return array_map(fn (Permission $permission): string => $permission->value, Permission::cases());
}
return array_keys($this->grantedFor($role));
}
/**
* @return array<string, bool>
*/
private function grantedFor(Role $role): array
{
return $this->granted[$role->id] ??= RolePermission::query()
->where('role_id', $role->id)
->pluck('permission')
// Ignore keys that no longer exist in the vocabulary.
->filter(fn (string $key): bool => Permission::tryFrom($key) !== null)
->mapWithKeys(fn (string $key): array => [$key => true])
->all();
}
}