0) { $result = DB::update( 'update user_api_tokens set revoked_at = NOW() where user_id = ? and (tenant_id = ? or tenant_id is null) and revoked_at is null', (string) $userId, (string) $tenantId ); } else { $result = DB::update( 'update user_api_tokens set revoked_at = NOW() where user_id = ? and revoked_at is null', (string) $userId ); } return $result !== false ? (int) $result : 0; } public static function revokeAllActiveByAdmin(): int { $result = DB::update( 'update user_api_tokens set revoked_at = NOW() where revoked_at is null and (expires_at is null or expires_at > NOW())' ); return $result !== false ? (int) $result : 0; } public static function listByUserId(int $userId, int $limit = 25): array { if ($userId <= 0) { return []; } if ($limit < 1) { $limit = 25; } elseif ($limit > 100) { $limit = 100; } $rows = DB::select( 'select id, uuid, user_id, name, selector, tenant_id, last_used_at, last_ip, expires_at, revoked_at, created_by, created from user_api_tokens where user_id = ? order by id desc limit ?', (string) $userId, (string) $limit ); return self::unwrapList($rows); } public static function countActiveForUser(int $userId): int { $count = DB::selectValue( 'select count(*) from user_api_tokens where user_id = ? and revoked_at is null and (expires_at is null or expires_at > NOW())', (string) $userId ); return $count ? (int) $count : 0; } public static function countActiveForUserExcludingId(int $userId, int $excludeId): int { if ($userId <= 0) { return 0; } $count = DB::selectValue( 'select count(*) from user_api_tokens where user_id = ? and id != ? and revoked_at is null and (expires_at is null or expires_at > NOW())', (string) $userId, (string) $excludeId ); return $count ? (int) $count : 0; } public static function countActive(): int { $count = DB::selectValue( 'select count(*) from user_api_tokens where revoked_at is null and (expires_at is null or expires_at > NOW())' ); return $count ? (int) $count : 0; } }