作者:lullabo
项目:mpx-ph
/**
* {@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);
}
}
作者:briareo
项目:aws-sdk-ph
/**
* 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);
}
作者:bobozhangsha
项目:HeartCar
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;
}
作者:ChenOhayo
项目:sitepoint_code
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');
}
}
作者:ghassan
项目:xiv-lodestone-php-ap
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);
}
}
作者:adurolm
项目:tinca
/**
*
* @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));
}
}
作者:schibsted-tech-polsk
项目:php-sndap
/**
* @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');
}
作者:NoviumDesig
项目:polefitnes
/**
* 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));
}
作者:OlivierBarbie
项目:google-api-php-clien
/**
* 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;
}
作者:CompanyOnTheWorl
项目:platformsh-cl
/**
* @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);
}
作者:gloob
项目:debug-bundl
/**
* @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);
}
作者:finix-payment
项目:processing-php-clien
/**
* @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;
}
作者:finix-payment
项目:processing-php-clien
/**
* @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;
}
}
作者:HeidiWang12
项目:our-world-in-data-graphe
/**
* 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();
}
作者:backupManage
项目:Twitter-API-PH
/**
* 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;
}
作者:fgross
项目:gitlab-ap
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);
}
作者:ryanwinchester-fork
项目:guzzle-service
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));
}
}
}
}
作者:JJVV2
项目:FantasyDataAP
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);
}
作者:GTAWWEKI
项目:tsiserver.u
/**
* 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);
}
}
作者:daskleinesy
项目:slimp
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);
}
}
}
}