$userId, 'keys' => $keys, ]; return $keys; } public static function getCachedPermissions(int $userId): array { if ($userId <= 0) { return []; } $cache = $_SESSION['permissions'] ?? null; if (is_array($cache) && (int) ($cache['user_id'] ?? 0) === $userId) { $keys = $cache['keys'] ?? []; return is_array($keys) ? $keys : []; } return []; } public static function clearUserCache(int $userId): void { $cache = $_SESSION['permissions'] ?? null; if (is_array($cache) && (int) ($cache['user_id'] ?? 0) === $userId) { unset($_SESSION['permissions']); } } public static function list(): array { return PermissionRepository::list(); } public static function listPaged(array $options): array { return PermissionRepository::listPaged($options); } public static function find(int $id): ?array { return PermissionRepository::find($id); } public static function findByKey(string $key): ?array { return PermissionRepository::findByKey($key); } public static function createFromAdmin(array $input): array { $form = self::sanitizeBase($input); $errors = self::validateBase($form); if ($errors) { return ['ok' => false, 'errors' => $errors, 'form' => $form]; } if (PermissionRepository::findByKey($form['key'])) { return ['ok' => false, 'errors' => [t('Permission key already exists')], 'form' => $form]; } $createdId = PermissionRepository::create($form); if (!$createdId) { return ['ok' => false, 'errors' => [t('Permission can not be created')], 'form' => $form]; } return ['ok' => true, 'form' => $form, 'id' => (int) $createdId]; } public static function updateFromAdmin(int $id, array $input): array { $form = self::sanitizeBase($input); $errors = self::validateBase($form); if ($errors) { return ['ok' => false, 'errors' => $errors, 'form' => $form]; } $existing = PermissionRepository::findByKey($form['key']); if ($existing && (int) ($existing['id'] ?? 0) !== $id) { return ['ok' => false, 'errors' => [t('Permission key already exists')], 'form' => $form]; } $updated = PermissionRepository::update($id, $form); if (!$updated) { return ['ok' => false, 'errors' => [t('Permission can not be updated')], 'form' => $form]; } return ['ok' => true, 'form' => $form]; } public static function deleteById(int $id): array { $permission = PermissionRepository::find($id); if (!$permission) { return ['ok' => false, 'status' => 404, 'error' => 'not_found']; } $deleted = PermissionRepository::delete($id); if (!$deleted) { return ['ok' => false, 'status' => 500, 'error' => 'delete_failed']; } return ['ok' => true, 'permission' => $permission]; } private static function sanitizeBase(array $input): array { return [ 'key' => trim((string) ($input['key'] ?? '')), 'description' => trim((string) ($input['description'] ?? '')), ]; } private static function validateBase(array $form): array { $errors = []; if ($form['key'] === '') { $errors[] = t('Permission key cannot be empty'); } elseif (!preg_match('/^[a-z0-9._-]+$/i', $form['key'])) { $errors[] = t('Permission key is invalid'); } return $errors; } }