/** * {@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); } }
/** * Always add a x-amz-content-sha-256 for data integrity. */ public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { if (!$request->hasHeader('x-amz-content-sha256')) { $request->setHeader('X-Amz-Content-Sha256', $this->getPayload($request)); } parent::signRequest($request, $credentials); }
public function after(GuzzleCommandInterface $command, RequestInterface $request, Operation $operation, array $context) { foreach ($this->buffered as $param) { $this->visitWithValue($command[$param->getName()], $param, $command); } $this->buffered = array(); $additional = $operation->getAdditionalParameters(); if ($additional && $additional->getLocation() == $this->locationName) { foreach ($command->toArray() as $key => $value) { if (!$operation->hasParam($key)) { $additional->setName($key); $this->visitWithValue($value, $additional, $command); } } $additional->setName(null); } // If data was found that needs to be serialized, then do so $xml = null; if ($this->writer) { $xml = $this->finishDocument($this->writer); } elseif ($operation->getData('xmlAllowEmpty')) { // Check if XML should always be sent for the command $writer = $this->createRootElement($operation); $xml = $this->finishDocument($writer); } if ($xml) { $request->setBody(Stream::factory($xml)); // Don't overwrite the Content-Type if one is set if ($this->contentType && !$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', $this->contentType); } } $this->writer = null; }
private function addExpectHeader(RequestInterface $request, StreamInterface $body) { // Determine if the Expect header should be used if ($request->hasHeader('Expect')) { return; } $expect = $request->getConfig()['expect']; // Return if disabled or if you're not using HTTP/1.1 if ($expect === false || $request->getProtocolVersion() !== '1.1') { return; } // The expect header is unconditionally enabled if ($expect === true) { $request->setHeader('Expect', '100-Continue'); return; } // By default, send the expect header when the payload is > 1mb if ($expect === null) { $expect = 1048576; } // Always add if the body cannot be rewound, the size cannot be // determined, or the size is greater than the cutoff threshold $size = $body->getSize(); if ($size === null || $size >= (int) $expect || !$body->isSeekable()) { $request->setHeader('Expect', '100-Continue'); } }
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); } }
/** * * @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)); } }
/** * @param RequestInterface $request * @param bool $acceptJsonResponse */ protected function buildRequest(RequestInterface $request, $acceptJsonResponse = true) { if ($acceptJsonResponse) { $request->addHeader('Accept', 'application/json'); } $request->addHeader('Accept-Charset', 'UTF-8'); }
/** * Asserts that the authorization header is correct. * * @param RequestInterface $request Request to test * * @return void */ protected function assertAuthorization(RequestInterface $request) { list($alg, $digest) = explode(' ', $request->getHeader('Authorization')); $this->assertEquals('Basic', $alg); $expected = self::MERCHANT_ID . ':' . self::SHARED_SECRET; $this->assertEquals($expected, base64_decode($digest)); }
/** * 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; }
/** * @param string $message * @param RequestInterface $request */ public function __construct($message = null, RequestInterface $request = null) { $message = $message ?: $this->message; if ($request !== null) { $message .= "\nRequest URL: " . $request->getUrl(); } parent::__construct($message, $this->code); }
/** * @param RequestInterface|ResponseInterface $message * @return string */ protected function formatHeaders($message) { $headers = []; foreach ($message->getHeaders() as $header => $value) { $headers[] = sprintf('%s: %s', $header, implode("\n : ", $value)); } return implode("\n", $headers); }
/** * @param RequestInterface $request * @param ResponseInterface $response * @return string */ protected function buildMessage($request, $response) { $resource = $this->getResponseBody(); if (is_null($resource)) { $resource = ''; } $message = sprintf('[url] %s [http method] %s [status code] %s [reason phrase] %s: %s', $request->getUrl(), $request->getMethod(), $response->getStatusCode(), $response->getReasonPhrase(), $resource); return $message; }
/** * @param RequestInterface $httpRequest The HTTP request before it is sent. * @return bool false if the request needs to be authorized */ private function isRequestAuthorized(RequestInterface $httpRequest) { $authorization = trim($httpRequest->getHeader('Authorization')); if (!$authorization) { return false; } else { return strpos($authorization, 'Basic') === 0; } }
/** * Gets the relevant data from the Guzzle clients. * * @param RequestInterface $request * @param ResponseInterface $response */ public function __construct(RequestInterface $request, ResponseInterface $response) { if ($response instanceof FutureResponse) { $this->httpStatusCode = null; } else { $this->httpStatusCode = $response->getStatusCode(); } $this->requestUrl = $request->getUrl(); }
/** * Set Headers for a Request specified by $headers. * * @param RequestInterface $request a Guzzle Request * @param array $headers headers to set (should be an assoc array). */ private function setGuzzleHeaders(RequestInterface $request, array $headers) { //iterate over the headers array and set each item foreach ($headers as $key => $value) { //Sets Header $request->setHeader($key, $value); } //return the request return $request; }
protected function assertRequestHasPostParameter($parameterName, $expectedValue, RequestInterface $request) { /** @var PostBody $requestBody */ $requestBody = $request->getBody(); $this->assertNotEmpty($requestBody); $this->assertInstanceOf(PostBody::class, $requestBody); $actualValue = $requestBody->getField($parameterName); $this->assertNotNull($actualValue, "The request should have the post body parameter '{$parameterName}'"); $this->assertEquals($expectedValue, $actualValue); }
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->setHeader($key, $additional->filter($value)); } } } }
public function __construct(RequestInterface $pRequest) { /** url parsing "formula" for resource */ list(, $subscription, $format, , $season, $week) = explode('/', $pRequest->getPath()); $file_partial = __DIR__ . '/' . implode('.', [$subscription, $format, $season, $week]); $headers = (include $file_partial . '.header.php'); $response_code = explode(' ', $headers[0])[1]; $mocked_response = file_get_contents($file_partial . '.body.' . $format); $stream = Stream\Stream::factory($mocked_response); parent::__construct($response_code, $headers, $stream); }
/** * Applies request headers to a request based on the POST state * * @param RequestInterface $request Request to update */ public function applyRequestHeaders(RequestInterface $request) { if ($this->files || $this->forceMultipart) { $request->setHeader('Content-Type', 'multipart/form-data; boundary=' . $this->getBody()->getBoundary()); } elseif ($this->fields) { $request->setHeader('Content-Type', 'application/x-www-form-urlencoded'); } if ($size = $this->getSize()) { $request->setHeader('Content-Length', $size); } }
public function after(GuzzleCommandInterface $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); } } } }
/** * Creates a Ring request from a request object. * * This function does not hook up the "then" and "progress" events that * would be required for actually sending a Guzzle request through a * RingPHP handler. * * @param RequestInterface $request Request to convert. * * @return array Converted Guzzle Ring request. */ public static function createRingRequest(RequestInterface $request) { $options = $request->getConfig()->toArray(); $url = $request->getUrl(); // No need to calculate the query string twice (in URL and query). $qs = ($pos = strpos($url, '?')) ? substr($url, $pos + 1) : null; return ['scheme' => $request->getScheme(), 'http_method' => $request->getMethod(), 'url' => $url, 'uri' => $request->getPath(), 'headers' => $request->getHeaders(), 'body' => $request->getBody(), 'version' => $request->getProtocolVersion(), 'client' => $options, 'query_string' => $qs, 'future' => isset($options['future']) ? $options['future'] : false]; }
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); } }
/** * {@inheritdoc} * Replaces the ewayCardNumber field in the body with "X"s. */ public function format(RequestInterface $request, ResponseInterface $response = null, \Exception $error = null, array $customData = array()) { $body = $request->getBody()->__toString(); $newBody = preg_replace_callback('/<ewayCardNumber>(.*?)<\\/ewayCardNumber>/', function ($matches) { $privateNumber = str_repeat('X', strlen($matches[1]) - 4) . substr($matches[1], -4); return '<ewayCardNumber modified>' . $privateNumber . '</ewayCardNumber>'; }, $body); $newRequest = clone $request; $newRequest->setBody(Stream::factory($newBody)); $request->setBody(Stream::factory($body)); return parent::format($newRequest, $response, $error, $customData); }
/** * 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); }
/** * @param string $message * @param RequestInterface $request * @param ResponseInterface $response */ public function __construct($message = null, RequestInterface $request = null, ResponseInterface $response = null) { $message = $message ?: $this->message; if ($request !== null && $response !== null) { $details = "[url] " . $request->getUrl(); $details .= " [status code] " . $response->getStatusCode(); $details .= " [reason phrase] " . $response->getReasonPhrase(); $details .= ApiResponseException::getErrorDetails($response); $message .= "\nDetails:\n " . wordwrap($details); } parent::__construct($message, $this->code); }
public function visit(GuzzleCommandInterface $command, RequestInterface $request, Parameter $param, array $context) { $body = $request->getBody(); if (!$body instanceof PostBodyInterface) { throw new \RuntimeException('Must be a POST body interface'); } $value = $param->filter($command[$param->getName()]); if (!$value instanceof PostFileInterface) { $value = new PostFile($param->getWireName(), $value); } $body->addFile($value); }
/** * @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]; }
private function shouldValidate(RequestInterface $request, ResponseInterface $response) { if ($request->getMethod() != 'GET' || $request->getConfig()->get('cache.disable')) { return false; } $validate = Utils::getDirective($request, 'Pragma') === 'no-cache' || Utils::getDirective($response, 'Pragma') === 'no-cache' || Utils::getDirective($request, 'must-revalidate') || Utils::getDirective($response, 'must-revalidate') || Utils::getDirective($request, 'no-cache') || Utils::getDirective($response, 'no-cache') || Utils::getDirective($response, 'max-age') === '0' || Utils::getDirective($response, 's-maxage') === '0'; // Use the strong ETag validator if available and the response contains // no Cache-Control directive if (!$validate && !$response->hasHeader('Cache-Control') && $response->hasHeader('ETag')) { $validate = true; } return $validate; }
function let(SiteConfigBuilder $siteConfigBuilder, SiteConfig $siteConfig, Factory $authenticatorFactory, ClientInterface $guzzle, Emitter $emitter, BeforeEvent $beforeEvent, CompleteEvent $completeEvent, RequestInterface $request, ResponseInterface $response, Factory $authenticatorFactory) { $siteConfig->getHost()->willReturn('example.com'); $siteConfigBuilder->buildForHost('example.com')->willReturn($siteConfig); $guzzle->getEmitter()->willReturn($emitter); $request->getHost()->willReturn('example.com'); $beforeEvent->getRequest()->willReturn($request); $beforeEvent->getClient()->willReturn($guzzle); $response->getBody()->willReturn('<html></html>'); $completeEvent->getResponse()->willReturn($response); $completeEvent->getRequest()->willReturn($request); $completeEvent->getClient()->willReturn($guzzle); $this->beConstructedWith($siteConfigBuilder, $authenticatorFactory); }
private function getRequestCookieValues(HttpRequest $request) { if (!$request->hasHeader('Cookie')) { return []; } $cookieStrings = explode(';', $request->getHeader('Cookie')); $values = []; foreach ($cookieStrings as $cookieString) { $cookieString = trim($cookieString); $currentValues = explode('=', $cookieString); $values[$currentValues[0]] = $currentValues[1]; } return $values; }