Example #1
0
 /**
  * Include an accessToken in a given apiHttpRequest.
  * @param Request $request
  * @return Request
  * @throws Exception
  */
 public function sign(Request $request)
 {
     // add the developer key to the request before signing it
     if ($this->client->getClassConfig($this, 'developer_key')) {
         $request->setQueryParam('key', $this->client->getClassConfig($this, 'developer_key'));
     }
     // Cannot sign the request without an OAuth access token.
     if (null == $this->token && null == $this->assertionCredentials) {
         return $request;
     }
     // Check if the token is set to expire in the next 30 seconds
     // (or has already expired).
     if ($this->isAccessTokenExpired()) {
         if ($this->assertionCredentials) {
             $this->refreshTokenWithAssertion();
         } else {
             $this->client->getLogger()->debug('OAuth2 access token expired');
             if (!array_key_exists('refresh_token', $this->token)) {
                 $error = "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->client->getLogger()->error($error);
                 throw new Exception($error);
             }
             $this->refreshToken($this->token['refresh_token']);
         }
     }
     $this->client->getLogger()->debug('OAuth2 authentication');
     // Add the OAuth2 header to the request
     $request->setRequestHeaders(array('Authorization' => 'Bearer ' . $this->token['access_token']));
     return $request;
 }
 /**
  * Check if an already cached request must be revalidated, and if so update
  * the request with the correct ETag headers.
  * @param Request $cached A previously cached response.
  * @param Request $request The outbound request.
  * return bool If the cached object needs to be revalidated, false if it is
  * still current and can be re-used.
  */
 protected function checkMustRevalidateCachedRequest($cached, $request)
 {
     if (CacheParser::mustRevalidate($cached)) {
         $addHeaders = array();
         if ($cached->getResponseHeader('etag')) {
             // [13.3.4] If an entity tag has been provided by the origin server,
             // we must use that entity tag in any cache-conditional request.
             $addHeaders['If-None-Match'] = $cached->getResponseHeader('etag');
         } elseif ($cached->getResponseHeader('date')) {
             $addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date');
         }
         $request->setRequestHeaders($addHeaders);
         return true;
     } else {
         return false;
     }
 }