*/ private array $resolved = []; public function for(User $user): PermissionSet { if (! $user->is_active) { return new PermissionSet([], [], []); } return $this->resolved[$user->id] ??= PermissionSet::fromArray(Cache::rememberForever( 'permissions.user.'.$user->id.'.'.self::version(), fn () => $this->resolve($user)->toArray(), )); } public static function flush(): void { Cache::forever(self::VERSION_KEY, self::version() + 1); app(self::class)->resolved = []; } public static function version(): int { return (int) Cache::get(self::VERSION_KEY, 1); } private function resolve(User $user): PermissionSet { $roleIds = DB::table('role_user')->where('user_id', $user->id)->distinct()->pluck('role_id')->map(fn ($id) => (int) $id)->all(); $global = []; $objects = []; $inherited = []; foreach (Grant::query()->whereIn('role_id', $roleIds)->get(['ability', 'resource_type', 'resource_id', 'include_children']) as $grant) { if ($grant->resource_type === null) { $global[$grant->ability] = true; } elseif ($grant->resource_id === null) { $objects[$grant->ability][$grant->resource_type] = true; } elseif (($objects[$grant->ability][$grant->resource_type] ?? null) !== true) { $objects[$grant->ability][$grant->resource_type][] = $grant->resource_id; if ($grant->include_children) { $inherited[$grant->resource_type][$grant->ability][] = $grant->resource_id; } } } // „Inkl. Unterobjekten“: Nachfahren einmalig auflösen – die Prüfung bleibt ein Array-Zugriff. // Hierarchische Typen leeren den Rechte-Cache, wenn sich ihr Baum ändert. $types = app(Abilities::class)->resourceTypes(); foreach ($inherited as $type => $byAbility) { $descendants = $types[$type]['descendants'] ?? null; foreach ($descendants ? $byAbility : [] as $ability => $ids) { if (is_array($objects[$ability][$type] ?? null)) { $objects[$ability][$type] = array_merge($objects[$ability][$type], array_map('intval', $descendants($ids))); } } } foreach ($objects as $ability => $types) { foreach ($types as $type => $ids) { if (is_array($ids)) { $objects[$ability][$type] = array_values(array_unique($ids)); } } } return new PermissionSet($roleIds, $global, $objects); } }