diff --git a/includes/utilities.php b/includes/utilities.php index 0445f6a..bec977f 100644 --- a/includes/utilities.php +++ b/includes/utilities.php @@ -48,14 +48,25 @@ function ensureUserHasApiKey($user) { /** * Executes a GET request to the given API endpoint and returns the JSON response as an associative array. * - * @param string $apiEndpoint The URL of the API endpoint to call + * Uses the v2 Torn API authentication scheme by sending the API key in an + * `Authorization: ApiKey ` header. The key is never transmitted as a + * query parameter. * - * @throws Exception If the API call fails or if the response is invalid JSON + * @param string $apiEndpoint The URL of the API endpoint to call + * @param string $apiKey The v2 API key to authenticate with + * + * @throws ApiKeyMissingException If the API key is empty + * @throws CurlErrorException If the cURL call fails + * @throws JsonDataException If the response body cannot be decoded as JSON * * @return array The JSON response from the API */ -function executeApiCall($apiEndpoint) { - $headers = ["Content-Type: application/json"]; +function executeApiCall($apiEndpoint, $apiKey) { + if (empty($apiKey)) { + throw new ApiKeyMissingException('API key is required for executeApiCall.'); + } + + $headers = ["Authorization: ApiKey $apiKey"]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $apiEndpoint); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); @@ -64,7 +75,7 @@ function executeApiCall($apiEndpoint) { $response = curl_exec($ch); if (curl_errno($ch)) { - throw new CurlErrorException("cURL error: " . curl_error($ch)); + throw new CurlErrorException('cURL error: ' . curl_error($ch)); } curl_close($ch); @@ -72,7 +83,7 @@ function executeApiCall($apiEndpoint) { $responseData = json_decode($response, true); if (json_last_error() !== JSON_ERROR_NONE) { - throw new JsonDataException("Failed to decode JSON response: " . json_last_error_msg()); + throw new JsonDataException('Failed to decode JSON response: ' . json_last_error_msg()); } return $responseData; @@ -238,3 +249,16 @@ function getSign($number) { return '$'; } + +/** + * Print a variable to the console for debugging purposes. + * + * @param mixed $data The data to print to the console. + * + * @return void + */ +function consoleLog( $data ) { + echo ''; +}