diff --git a/includes/utilities.php b/includes/utilities.php index 5ea4211..1826f39 100644 --- a/includes/utilities.php +++ b/includes/utilities.php @@ -14,6 +14,11 @@ * @link https://github.com/ksolomon/Torn-Vault-Tracker */ +// Test hook for fetchLiveVaultBalance(). When set, this closure is called +// instead of executeApiCall. Set $GLOBALS['liveBalanceTestHook'] to a +// closure($url, $apiKey): array in test code. Production code leaves it null. +$GLOBALS['liveBalanceTestHook'] = $GLOBALS['liveBalanceTestHook'] ?? null; + /** * Checks if the database is new and empty. * @@ -332,3 +337,54 @@ function backfillRunningBalances($pdo, $user) { $updateStmt->bindValue(':user', $user); $updateStmt->execute(); } + +/** + * Fetch the live vault balance for a user from the v2 /money endpoint. + * + * Returns the `money.vault` value as an int, or null if the API call + * fails, returns invalid JSON, or doesn't include `money.vault`. The + * result is cached for the duration of the PHP request so multiple + * callers (e.g., `vaultLoop` for one user, then the all-users sum) + * don't re-fetch. + * + * @param string $user The user whose vault balance to fetch. + * + * @return int|null The vault amount in pennies, or null on failure. + */ +function fetchLiveVaultBalance($user) { + static $cache = null; + + if ($cache === null) { + $cache = new WeakMap(); + } + + $hook = $GLOBALS['liveBalanceTestHook'] ?? null; + $cacheKey = $hook ?? true; + + if (isset($cache[$cacheKey]) && array_key_exists($user, $cache[$cacheKey])) { + return $cache[$cacheKey][$user]; + } + + if (!array_key_exists($user, USER_KEYS)) { + return null; + } + + $url = 'https://api.torn.com/v2/user?selections=money'; + try { + $responseData = $hook !== null + ? $hook($url, USER_KEYS[$user]) + : executeApiCall($url, USER_KEYS[$user]); + + if (!isset($responseData['money']['vault'])) { + return null; + } + + if (!isset($cache[$cacheKey])) { + $cache[$cacheKey] = []; + } + $cache[$cacheKey][$user] = (int)$responseData['money']['vault']; + return $cache[$cacheKey][$user]; + } catch (Exception $e) { + return null; + } +}