public function sign(HttpRequest $request) { if ($this->key) { $request->setUrl($request->getUrl() . (strpos($request->getUrl(), '?') === false ? '?' : '&') . 'key=' . urlencode($this->key)); } return $request; }
/** * Decode an HTTP Response. * @static * @throws Service\Exception * @param HttpRequest $response The http response to be decoded. * @return mixed|null */ public static function decodeHttpResponse($response) { $code = $response->getResponseHttpCode(); $body = $response->getResponseBody(); $decoded = null; if ($code != '200' && $code != '201' && $code != '204') { $decoded = json_decode($body, true); $err = 'Error calling ' . $response->getRequestMethod() . ' ' . $response->getUrl(); if ($decoded != null && isset($decoded['error']['message']) && isset($decoded['error']['code'])) { // if we're getting a json encoded error definition, use that instead of the raw response // body for improved readability $err .= ": ({$decoded['error']['code']}) {$decoded['error']['message']}"; } else { $err .= ": ({$code}) {$body}"; } throw new Service\Exception($err, $code); } // Only attempt to decode the response, if the response code wasn't (204) 'no content' if ($code != '204') { $decoded = json_decode($body, true); if ($decoded == null) { throw new Service\Exception("Invalid json in service response: {$body}"); } } return $decoded; }
/** * Include an accessToken in a given HttpRequest. * @param HttpRequest $request * @return HttpRequest * @throws Exception */ public function sign(HttpRequest $request) { // add the developer key to the request before signing it if ($this->developerKey) { $requestUrl = $request->getUrl(); $requestUrl .= strpos($request->getUrl(), '?') === false ? '?' : '&'; $requestUrl .= 'key=' . urlencode($this->developerKey); $request->setUrl($requestUrl); } // Cannot sign the request without an OAuth access token. if (null == $this->accessToken && null == $this->assertionCredentials) { return $request; } // If the token is set to expire in the next 30 seconds (or has already // expired), refresh it and set the new token. $expired = null == $this->accessToken || $this->accessToken['created'] + ($this->accessToken['expires_in'] - 30) < time(); if ($expired) { if ($this->assertionCredentials) { $this->refreshTokenWithAssertion(); } else { if (!array_key_exists('refresh_token', $this->accessToken)) { throw new Exception("The OAuth 2.0 access token has expired, " . "and a refresh token is not available. Refresh tokens are not " . "returned for responses that were auto-approved."); } $this->refreshToken($this->accessToken['refresh_token']); } } // Add the OAuth2 header to the request $request->setRequestHeaders(array('Authorization' => 'Bearer ' . $this->accessToken['access_token'])); return $request; }