Exemplo n.º 1
0
 /**
  * {@inheritdoc}
  *
  * @return array
  */
 public function send(RequestInterface $request)
 {
     // Disable HTTP error codes unless requested so that we can parse out
     // the errors ourselves.
     if (!$request->getQuery()->hasKey('httpError')) {
         $request->getQuery()->set('httpError', 'false');
     }
     $response = parent::send($request);
     // Parse out exceptions from the response body.
     $contentType = $response->getHeader('Content-Type');
     if (preg_match('~^(application|text)/json~', $contentType)) {
         // @todo Figure out how we can support the big_int_string option here.
         // @see http://stackoverflow.com/questions/19520487/json-bigint-as-string-removed-in-php-5-5
         $data = $response->json();
         if (!empty($data['responseCode']) && !empty($data['isException'])) {
             throw new ApiException("Error {$data['title']} on request to {$request->getUrl()}: {$data['description']}", (int) $data['responseCode']);
         } elseif (!empty($data[0]['entry']['responseCode']) && !empty($data[0]['entry']['isException'])) {
             throw new ApiException("Error {$data[0]['entry']['title']} on request to {$request->getUrl()}: {$data[0]['entry']['description']}", (int) $data[0]['entry']['responseCode']);
         }
         return $data;
     } elseif (preg_match('~^(application|text)/(atom\\+)?xml~', $contentType)) {
         if (strpos((string) $response->getBody(), 'xmlns:e="http://xml.theplatform.com/exception"') !== FALSE) {
             if (preg_match('~<e:title>(.+)</e:title><e:description>(.+)</e:description><e:responseCode>(.+)</e:responseCode>~', (string) $response->getBody(), $matches)) {
                 throw new ApiException("Error {$matches[1]} on request to {$request->getUrl()}: {$matches[2]}", (int) $matches[3]);
             } elseif (preg_match('~<title>(.+)</title><summary>(.+)</summary><e:responseCode>(.+)</e:responseCode>~', (string) $response->getBody(), $matches)) {
                 throw new ApiException("Error {$matches[1]} on request to {$request->getUrl()}: {$matches[2]}", (int) $matches[3]);
             }
         }
         $data = $response->xml();
         $data = array($data->getName() => static::convertXmlToArray($data));
         return $data;
     } else {
         throw new ParseException("Unable to handle response with type {$contentType}.", $response);
     }
 }
 /**
  * @param RequestInterface $request
  * @return array ['query' => ..., 'request' => ...]
  */
 protected function getRequestAndQuery(RequestInterface $request)
 {
     $query = [];
     foreach ($request->getQuery() as $param => $val) {
         $query[$param] = $val;
     }
     $requestInfo = ['url' => $request->getUrl(), 'path' => $request->getPath(), 'queryString' => (string) $request->getQuery(), 'method' => $request->getMethod(), 'hostname' => $request->getHost(), 'port' => $request->getPort(), 'resource' => $request->getResource()];
     return ['query' => $query, 'request' => $requestInfo];
 }
Exemplo n.º 3
0
 /**
  * 
  * @param RequestInterface $request
  * @param array $params
  */
 protected function setRequestParams(RequestInterface $request, $params = array())
 {
     $query = $request->getQuery();
     foreach ($params as $param) {
         $query->set(key($param), current($param));
     }
 }
Exemplo n.º 4
0
 /**
  * Decode an HTTP Response.
  * @static
  * @throws Google_Service_Exception
  * @param GuzzleHttp\Message\RequestInterface $response The http response to be decoded.
  * @param GuzzleHttp\Message\ResponseInterface $response
  * @return mixed|null
  */
 public static function decodeHttpResponse(ResponseInterface $response, RequestInterface $request = null)
 {
     $body = (string) $response->getBody();
     $code = $response->getStatusCode();
     $result = null;
     // return raw response when "alt" is "media"
     $isJson = !($request && 'media' == $request->getQuery()->get('alt'));
     // set the result to the body if it's not set to anything else
     if ($isJson) {
         try {
             $result = $response->json();
         } catch (ParseException $e) {
             $result = $body;
         }
     } else {
         $result = $body;
     }
     // retry strategy
     if (intVal($code) >= 300) {
         $errors = null;
         // Specific check for APIs which don't return error details, such as Blogger.
         if (isset($result['error']) && isset($result['error']['errors'])) {
             $errors = $result['error']['errors'];
         }
         throw new Google_Service_Exception($body, $code, null, $errors);
     }
     return $result;
 }
 public function buildRequest(GuzzleRequestInterface $request)
 {
     if (!$this->query) {
         throw new \UnexpectedValueException(sprintf('CharacterSearchRequest requires at least a search query.'));
     }
     $query = $request->getQuery();
     $query->set('q', $this->getQuery());
     if ($this->getClass()) {
         $query->set('classjob', $this->getClass());
     }
     if ($this->getWorld()) {
         $query->set('worldname', $this->getWorld());
     }
     if ($this->getRace()) {
         $query->set('race_tribe', $this->getRace());
     }
     if ($this->getGrandCompanies()) {
         $query->set('gcid', $this->getGrandCompanies());
     }
     if ($this->getLanguages()) {
         $query->set('blog_lang', $this->getLanguages());
     }
     if ($this->getPage()) {
         $query->set('page', $this->getPage());
     }
     if ($this->getOrder()) {
         $query->set('order', $this->getOrder());
     } else {
         $query->set('order', static::ORDER_NAME_ASC);
     }
 }
 public function after(CommandInterface $command, RequestInterface $request, Operation $operation, array $context)
 {
     $additional = $operation->getAdditionalParameters();
     if ($additional && $additional->getLocation() == $this->locationName) {
         foreach ($command->toArray() as $key => $value) {
             if (!$operation->hasParam($key)) {
                 $request->getQuery()[$key] = $this->prepareValue($value, $additional);
             }
         }
     }
 }
Exemplo n.º 7
0
 /**
  * Signs the specified request with an SellerCenter API signing protocol by using the
  * provided SellerCenter API credentials and adding the required headers to the request
  *
  * @param RequestInterface     $request     Request to add a signature to
  * @param CredentialsInterface $credentials Signing credentials
  */
 public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
 {
     $parameters = $request->getQuery()->toArray();
     $parameters['UserID'] = $credentials->getId();
     $parameters['Version'] = '1.0';
     $parameters['Action'] = $request->getConfig()->get('command')->getName();
     $parameters['Timestamp'] = gmdate(DateTime::ISO8601);
     // the keys MUST be in alphabetical order to correct signature calculation
     ksort($parameters);
     $parameters['Signature'] = rawurlencode(hash_hmac('sha256', http_build_query($parameters, '', '&', PHP_QUERY_RFC3986), $credentials->getKey(), false));
     $request->setQuery($parameters);
 }
 public function buildRequest(GuzzleRequestInterface $request)
 {
     if (!$this->id) {
         throw new \UnexpectedValueException(sprintf('FreeCompanyMemberListRequest requires a free company ID.'));
     }
     $query = $request->getQuery();
     if ($this->getOrder()) {
         $query->set('order', $this->getOrder());
     } else {
         $query->set('order', static::ORDER_NAME_ASC);
     }
 }
Exemplo n.º 9
0
 protected function clientCall($path, $method = 'GET', $data = array())
 {
     if ($this->request instanceof RequestInterface) {
         $this->request = $this->client->createRequest($method);
     }
     $this->request->setPath($path);
     $this->request->setMethod($method);
     $this->request->setQuery($data);
     if (isset($this->accessToken)) {
         $this->request->getQuery()->set('access_token', $this->accessToken);
     }
     $response = $this->client->send($this->request);
     return $response->json();
 }
Exemplo n.º 10
0
 /**
  * Calculate signature for request
  *
  * This method mostly copy pasted from original class, except its bottom part where we actually hashing our request
  *
  * @param RequestInterface $request Request to generate a signature for
  * @param array $params Oauth parameters.
  *
  * @return string
  */
 public function getSignature(RequestInterface $request, array $params)
 {
     // Remove oauth_signature if present
     // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
     unset($params['oauth_signature']);
     // Add POST fields if the request uses POST fields and no files
     $body = $request->getBody();
     if ($body instanceof PostBodyInterface && !$body->getFiles()) {
         $query = Query::fromString($body->getFields(true));
         $params += $query->toArray();
     }
     // Parse & add query string parameters as base string parameters
     $query = Query::fromString((string) $request->getQuery());
     $query->setEncodingType(Query::RFC1738);
     $params += $query->toArray();
     $baseString = $this->createBaseString($request, $this->prepareParameters($params));
     // changed code
     return base64_encode(hash_hmac('sha1', $baseString, $this->consumer_secret, true));
 }
Exemplo n.º 11
0
 /**
  * 
  * @param HttpRequest $request
  * @return HttpRequest
  */
 private function deEncodeRequestUrl(HttpRequest $request)
 {
     $request->getQuery()->setEncodingType(false);
     return $request;
 }
Exemplo n.º 12
0
 /**
  * Decode an HTTP Response.
  * @static
  * @throws Google_Service_Exception
  * @param GuzzleHttp\Message\RequestInterface $response The http response to be decoded.
  * @param GuzzleHttp\Message\ResponseInterface $response
  * @return mixed|null
  */
 public static function decodeHttpResponse(ResponseInterface $response, RequestInterface $request = null)
 {
     $body = (string) $response->getBody();
     $code = $response->getStatusCode();
     // retry strategy
     if (intVal($code) >= 300) {
         $errors = null;
         $result = $response->json();
         // Specific check for APIs which don't return error details, such as Blogger.
         if (isset($result['error']) && isset($result['error']['errors'])) {
             $errors = $result['error']['errors'];
         }
         throw new Google_Service_Exception($body, $code, null, $errors);
     }
     // return raw response when "alt" is "media"
     if ($request && $request->getQuery()->get('alt') == 'media') {
         return $body;
     }
     return $response->json();
 }
Exemplo n.º 13
0
 private function moveHeadersToQuery(RequestInterface $request)
 {
     $query = $request->getQuery();
     foreach ($request->getHeaders() as $name => $header) {
         $name = strtolower($name);
         if (substr($name, 0, 5) == 'x-amz') {
             $query[$name] = $header;
         }
         if ($name !== 'host') {
             $request->removeHeader($name);
         }
     }
 }
Exemplo n.º 14
0
 private function createCanonicalizedResource(RequestInterface $request)
 {
     $data = $this->parser->parse($request->getUrl());
     $buffer = '/';
     if ($data['bucket']) {
         $buffer .= $data['bucket'];
         if (!empty($data['key']) || !$data['path_style']) {
             $buffer .= '/' . $data['key'];
         }
     }
     // Add sub resource parameters
     $query = $request->getQuery();
     $first = true;
     foreach ($this->signableQueryString as $key) {
         if ($query->hasKey($key)) {
             $value = $query[$key];
             $buffer .= $first ? '?' : '&';
             $first = false;
             $buffer .= $key;
             // Don't add values for empty sub-resources
             if (strlen($value)) {
                 $buffer .= "={$value}";
             }
         }
     }
     return $buffer;
 }
Exemplo n.º 15
0
 /**
  * Calculate signature for request
  *
  * @param RequestInterface $request Request to generate a signature for
  * @param array            $params  Oauth parameters.
  *
  * @return string
  *
  * @throws \RuntimeException
  */
 public function getSignature(RequestInterface $request, array $params)
 {
     // Remove oauth_signature if present
     // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
     unset($params['oauth_signature']);
     // Add POST fields if the request uses POST fields and no files
     $body = $request->getBody();
     if ($body instanceof PostBodyInterface && !$body->getFiles()) {
         $query = Query::fromString($body->getFields(true));
         $params += $query->toArray();
     }
     // Parse & add query string parameters as base string parameters
     $query = Query::fromString((string) $request->getQuery());
     $query->setEncodingType(Query::RFC1738);
     $params += $query->toArray();
     $baseString = $this->createBaseString($request, $this->prepareParameters($params));
     // Implements double-dispatch to sign requests
     switch ($this->config['signature_method']) {
         case Oauth1::SIGNATURE_METHOD_HMAC:
             $signature = $this->signUsingHmacSha1($baseString);
             break;
         case Oauth1::SIGNATURE_METHOD_RSA:
             $signature = $this->signUsingRsaSha1($baseString);
             break;
         case Oauth1::SIGNATURE_METHOD_PLAINTEXT:
             $signature = $this->signUsingPlaintext($baseString);
             break;
         default:
             throw new \RuntimeException('Unknown signature method: ' . $this->config['signature_method']);
             break;
     }
     return base64_encode($signature);
 }
Exemplo n.º 16
0
 /**
  * Handle an error. We handle errors by throwing an exception.
  *
  * @param string $error An error code representing the error
  *                      (use_underscore_separators).
  * @param string|null $message The error message.
  * @param \GuzzleHttp\Message\RequestInterface|null $request Optional. The
  *                                                  Guzzle request object.
  * @param \GuzzleHttp\Message\ResponseInterface|null $response Optional. The
  *                                                   Guzzle response object.
  *
  * @return void
  * @throws \Box\View\BoxViewException
  */
 protected static function error($error, $message = null, $request = null, $response = null)
 {
     if (!empty($request)) {
         $message .= "\n";
         $message .= 'Method: ' . $request->getMethod() . "\n";
         $message .= 'URL: ' . $request->getUrl() . "\n";
         $message .= 'Query: ' . json_encode($request->getQuery()->toArray()) . "\n";
         $message .= 'Headers: ' . json_encode($request->getHeaders()) . "\n";
         $message .= 'Request Body: ' . $request->getBody() . "\n";
     }
     if (!empty($response)) {
         $message .= "\n";
         $message .= 'Response Body: ' . $response->getBody() . "\n";
     }
     $exception = new BoxViewException($message);
     $exception->errorCode = $error;
     throw $exception;
 }
Exemplo n.º 17
0
 /**
  * @param RequestInterface $request
  * @param ResponseInterface $response
  * @return object
  */
 protected function parseResponse(RequestInterface $request, ResponseInterface $response)
 {
     $this->response = $response;
     if ($request->getQuery()->get('check_if_alive') == '1') {
         $xml = $response->xml();
         return (object) array($xml->getName() => (string) $xml);
     }
     return $response->json();
 }
Exemplo n.º 18
0
 private function applyQuery(RequestInterface $request, $name, Shape $member, $value)
 {
     if ($value !== null) {
         $request->getQuery()->set($member['locationName'] ?: $name, $value);
     }
 }
 /**
  * Calculate signature for request
  *
  * @param RequestInterface $request Request to generate a signature for
  *
  * @return string
  */
 public function getSignature(RequestInterface $request)
 {
     // For POST|PUT set the JSON body string as the params
     if ($request->getMethod() == 'POST' || $request->getMethod() == 'PUT') {
         $params = $request->getBody()->__toString();
         /**
          * If you don't seek() back to the beginning then attempting to
          * send a JSON body > 1MB will probably fail.
          *
          * @link http://stackoverflow.com/q/32359664/99071
          * @link https://groups.google.com/forum/#!topic/guzzle/vkF5druf6AY
          */
         $request->getBody()->seek(0);
         // Make sure to remove any other query params
         $request->setQuery([]);
     } else {
         $params = Query::fromString($request->getQuery(), Query::RFC1738)->toArray();
         $params = $this->prepareParameters($params);
         // Re-Set the query to the properly ordered query string
         $request->setQuery($params);
         $request->getQuery()->setEncodingType(Query::RFC1738);
     }
     $baseString = $this->createBaseString($request, $params);
     return base64_encode($this->sign_HMAC_SHA256($baseString));
 }
Exemplo n.º 20
0
 /**
  * Collect & sanitize data about a Guzzle request.
  *
  * @param RequestInterface $request Guzzle request.
  * @return array
  */
 private function collectRequest(RequestInterface $request)
 {
     $query = $request->getQuery();
     return ['headers' => $request->getHeaders(), 'method' => $request->getMethod(), 'scheme' => $request->getScheme(), 'host' => $request->getHost(), 'path' => $request->getPath(), 'query' => (string) $query, 'queryParams' => $query->toArray(), 'body' => (string) $request->getBody()];
 }
Exemplo n.º 21
0
 private function add_query(RequestInterface $request, $value)
 {
     if ($value instanceof Query) {
         $original = $request->getQuery();
         // Do not overwrite existing query string variables by overwriting
         // the object with the query string data passed in the URL
         $request->setQuery($value->overwriteWith($original->toArray()));
     } elseif (is_array($value)) {
         // Do not overwrite existing query string variables
         $query = $request->getQuery();
         foreach ($value as $k => $v) {
             if (!isset($query[$k])) {
                 $query[$k] = $v;
             }
         }
     } else {
         throw new \InvalidArgumentException('query value must be an array ' . 'or Query object');
     }
 }
Exemplo n.º 22
0
 /**
  * Calculate signature for request
  *
  * @param RequestInterface $request Request to generate a signature for
  *
  * @return string
  *
  * @throws \RuntimeException
  */
 public function getSignature(RequestInterface $request)
 {
     // For POST|PUT set the JSON body string as the params
     if ($request->getMethod() == 'POST' || $request->getMethod() == 'PUT') {
         $params = $request->getBody()->__toString();
         // Make sure to remove any other query params
         $request->setQuery([]);
     } else {
         $params = Query::fromString($request->getQuery(), Query::RFC1738)->toArray();
         $params = $this->prepareParameters($params);
         // Re-Set the query to the properly ordered query string
         $request->setQuery($params);
         $request->getQuery()->setEncodingType(Query::RFC1738);
     }
     $baseString = $this->createBaseString($request, $params);
     return base64_encode($this->sign_HMAC_SHA256($baseString));
 }
Exemplo n.º 23
0
 protected function assertRequestHasQueryParameter($parameterName, $expectedValue, RequestInterface $request)
 {
     $actualValue = $request->getQuery()->get($parameterName);
     $this->assertNotNull($actualValue, "The request should have the query parameter '{$parameterName}'");
     $this->assertEquals($expectedValue, $actualValue);
 }
Exemplo n.º 24
0
 /**
  * Calculate signature for request
  *
  * @param RequestInterface $request Request to generate a signature for
  * @param array            $params  Oauth parameters.
  *
  * @return string
  *
  * @throws \RuntimeException
  */
 public function getSignature(RequestInterface $request, array $params)
 {
     // Remove oauth_signature if present
     // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
     unset($params['oauth_signature']);
     // Add POST fields if the request uses POST fields and no files
     $body = $request->getBody();
     if ($body instanceof PostBodyInterface && !$body->getFiles()) {
         $query = Query::fromString($body->getFields(true));
         $params += $query->toArray();
     }
     // Parse & add query string parameters as base string parameters
     $query = Query::fromString((string) $request->getQuery());
     $query->setEncodingType(Query::RFC1738);
     $params += $query->toArray();
     $baseString = $this->createBaseString($request, $this->prepareParameters($params));
     // Implements double-dispatch to sign requests
     $meth = [$this, 'sign_' . str_replace('-', '_', $this->config['signature_method'])];
     if (!is_callable($meth)) {
         throw new \RuntimeException('Unknown signature method: ' . $this->config['signature_method']);
     }
     return base64_encode(call_user_func($meth, $baseString, $this->config));
 }
Exemplo n.º 25
0
 /**
  * @param RequestInterface $actual
  * @param RequestInterface $expected
  * @throws FailedRequestExpectationException
  */
 private static function checkRequestQuery(RequestInterface $actual, RequestInterface $expected)
 {
     $paramsA = $actual->getQuery()->toArray();
     $paramsB = $expected->getQuery()->toArray();
     self::checkIsArrayEqual($paramsA, $paramsB, 'query params');
 }