Esempio n. 1
0
 /**
  * @param RequestInterface $request
  * @param string $type
  */
 protected function logRequest(RequestInterface $request, $type = 'http')
 {
     $args = [ucfirst($type), $request->getMethod(), $request->getUri()];
     /** @noinspection PrintfScanfArgumentsInspection */
     $this->log(sprintf(' ==> (%s) %s %s', ...$args));
     $headers = $this->removeTokenFromLogs($request->getHeaders());
     $this->log('  Request headers: ' . json_encode($headers), Logger::DEBUG);
     $size = strlen($request->getBody());
     if ($size > 0) {
         $this->log(sprintf('  Request body (%sb): %s', $size, $request->getBody()), Logger::DEBUG);
     }
 }
Esempio n. 2
0
 /**
  * Initialise les valeurs des champs POST
  * @return void
  */
 private function initPost()
 {
     $this->post = array();
     if (!$this->request->getBody()->getSize()) {
         return;
     }
     if (trim($this->request->getBody()->read($this->request->getBody()->getSize()))) {
         foreach (explode('&', $this->request->getBody()) as $couple) {
             $vals = explode('=', $couple);
             $this->post[$vals[0]] = rawurldecode($vals[1]);
         }
     }
 }
Esempio n. 3
0
 public function send(RequestInterface $request)
 {
     switch ($request->getUri()->getPath()) {
         case '/documents/1':
             if ('GET' === $request->getMethod()) {
                 return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_1.json'));
             }
             break;
         case '/documents/2':
             if ('GET' === $request->getMethod()) {
                 return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_2.json'));
             }
             break;
         case '/documents/3':
             if ('GET' === $request->getMethod()) {
                 return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_3.json'));
             }
             break;
         case '/documents/4':
             if ('DELETE' === $request->getMethod()) {
                 return new Response(204, ['Content-Type' => 'text/html']);
             }
             if ('PUT' === $request->getMethod()) {
                 if ('{"title":"Test 4 changed","body":"Lorem ipsum"}' === $request->getBody()->getContents()) {
                     return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_4_changed.json'));
                 }
             }
             if ('GET' === $request->getMethod()) {
                 return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents_4.json'));
             }
             break;
         case '/documents':
             if ('POST' === $request->getMethod()) {
                 if ('{"title":"Test 4","body":"Lorem ipsum"}' === $request->getBody()->getContents()) {
                     return new Response(201, ['Location' => '/documents/4']);
                 }
             }
             if ('GET' === $request->getMethod()) {
                 return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/documents.json'));
             }
             break;
         case '':
             if ('GET' === $request->getMethod()) {
                 return new Response(200, ['Content-Type' => 'application/hal+json'], file_get_contents(__DIR__ . '/fixtures/root.json'));
             }
             break;
         default:
             return new Response(404);
     }
     return new Response(405, ['Content-Type' => 'text/plain'], sprintf('No route found for "%s %s": Method Not Allowed', $request->getUri()->getPath(), $request->getMethod()));
 }
 /**
  * Starts the profiling.
  * @param RequestInterface $request
  */
 public function enter(RequestInterface $request = null)
 {
     $this->starts = ['wt' => microtime(true), 'mu' => memory_get_usage(), 'pmu' => memory_get_peak_usage()];
     if ($request) {
         $this->request = ['method' => $request->getMethod(), 'url' => (string) $request->getUri(), 'body' => (string) $request->getBody()];
     }
 }
 private function fetchResumeUri()
 {
     $result = null;
     $body = $this->request->getBody();
     if ($body) {
         $headers = array('content-type' => 'application/json; charset=UTF-8', 'content-length' => $body->getSize(), 'x-upload-content-type' => $this->mimeType, 'x-upload-content-length' => $this->size, 'expect' => '');
         foreach ($headers as $key => $value) {
             $this->request = $this->request->withHeader($key, $value);
         }
     }
     $response = $this->client->execute($this->request, false);
     $location = $response->getHeaderLine('location');
     $code = $response->getStatusCode();
     if (200 == $code && true == $location) {
         return $location;
     }
     $message = $code;
     $body = json_decode((string) $this->request->getBody(), true);
     if (isset($body['error']['errors'])) {
         $message .= ': ';
         foreach ($body['error']['errors'] as $error) {
             $message .= "{$error[domain]}, {$error[message]};";
         }
         $message = rtrim($message, ';');
     }
     $error = "Failed to start the resumable upload (HTTP {$message})";
     $this->client->getLogger()->error($error);
     throw new GoogleException($error);
 }
 /**
  * Render a PSR-7 request.
  *
  * @param RequestInterface $request
  * @return string
  */
 public function renderRequest(RequestInterface $request)
 {
     $return = '';
     $return .= sprintf("URL:     %s\n", $request->getUri());
     $return .= sprintf("METHOD:  %s\n", $request->getMethod());
     if ($request->getHeaders()) {
         $return .= 'HEADERS:';
     }
     $indent = false;
     foreach ($request->getHeaders() as $name => $values) {
         if ($indent) {
             $return .= str_repeat(' ', 8);
         }
         $return .= sprintf(" %s: %s\n", $name, implode(', ', $values));
         $indent = true;
     }
     if ($body = (string) $request->getBody()) {
         $return .= 'BODY:    ';
         switch ($request->getHeaderLine('Content-Type')) {
             case 'application/json':
                 $return .= json_encode(json_decode($body, true), JSON_PRETTY_PRINT);
                 break;
             default:
                 $return .= $body;
                 break;
         }
         $return .= "\n";
     }
     return $return;
 }
Esempio n. 7
0
 public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
 {
     $params = Psr7\parse_query($request->getBody()->__toString());
     $params['SignatureVersion'] = '2';
     $params['SignatureMethod'] = 'HmacSHA256';
     $params['AWSAccessKeyId'] = $credentials->getAccessKeyId();
     if ($credentials->getSecurityToken()) {
         $params['MWSAuthToken'] = $credentials->getSecurityToken();
     }
     $params['Timestamp'] = gmdate(self::ISO8601_BASIC);
     ksort($params);
     $canonicalizedQueryString = $this->getCanonicalizedQuery($params);
     $stringToSign = implode("\n", [$request->getMethod(), $request->getUri()->getHost(), $request->getUri()->getPath(), $canonicalizedQueryString]);
     // calculate HMAC with SHA256 and base64-encoding
     $signature = base64_encode(hash_hmac('sha256', $stringToSign, $credentials->getSecretKey(), TRUE));
     // encode the signature for the request
     $signature = str_replace('%7E', '~', rawurlencode($signature));
     $signature = str_replace('+', '%20', $signature);
     $signature = str_replace('*', '%2A', $signature);
     $queryString = $canonicalizedQueryString . "&Signature=" . $signature;
     if ($request->getMethod() === 'POST') {
         return new Request('POST', $request->getUri(), ['Content-Length' => strlen($queryString), 'Content-Type' => 'application/x-www-form-urlencoded'], $queryString);
     } else {
         return new Request('GET', $request->getUri()->withQuery($queryString));
     }
 }
Esempio n. 8
0
 /**
  * @param RequestInterface $request
  * @return Message
  */
 public function convertRequestToMessage(RequestInterface $request)
 {
     parse_str($request->getBody(), $body);
     $message = new Message($body['Message-Id']);
     $message->setSubject($body['Subject']);
     if (!empty($body['Reply-To'])) {
         $message->setReplyTo($body['Reply-To']);
     } elseif (!empty($body['Reply-to'])) {
         $message->setReplyTo($body['Reply-to']);
     } elseif (!empty($body['reply-to'])) {
         $message->setReplyTo($body['reply-to']);
     }
     if (!empty($body['From'])) {
         $message->setFrom($body['From']);
     } else {
         $message->setFrom($body['from']);
     }
     if (isset($body['To'])) {
         $message->setTo($body['To']);
     }
     if (!empty($body['body-html'])) {
         $message->setBodyHtml($body['body-html']);
     }
     if (!empty($body['stripped-html'])) {
         $body['stripped-html'] = html_entity_decode($body['stripped-html']);
         if (strpos($body['stripped-html'], 'ĂĄ') !== false && stripos($body['stripped-html'], 'charset=iso-8859-2')) {
             $body['stripped-html'] = iconv('UTF-8', 'ISO-8859-2//TRANSLIT', $body['stripped-html']);
         } elseif (strpos($body['stripped-html'], 'á') !== false && stripos($body['stripped-html'], 'charset=windows-1250')) {
             $body['stripped-html'] = iconv('UTF-8', 'CP1250//TRANSLIT', $body['stripped-html']);
         }
         $message->setStrippedHtml($body['stripped-html']);
     }
     if (!empty($body['body-plain'])) {
         if (isset($body['stripped-html'])) {
             if (strpos($body['body-plain'], 'ĂĄ') !== false && stripos($body['stripped-html'], 'charset=iso-8859-2')) {
                 $body['body-plain'] = iconv('UTF-8', 'ISO-8859-2//TRANSLIT', $body['body-plain']);
             } elseif (strpos($body['body-plain'], 'á') !== false && stripos($body['stripped-html'], 'charset=windows-1250')) {
                 $body['body-plain'] = iconv('UTF-8', 'CP1250//TRANSLIT', $body['body-plain']);
             }
         }
         $message->setBodyPlain($body['body-plain']);
     }
     if (!empty($body['References'])) {
         $message->setReferences($body['References']);
     }
     $message->setDate((new \DateTime())->setTimestamp($body['timestamp']));
     $message->setSpam(isset($body['X-Mailgun-Sflag']) && $body['X-Mailgun-Sflag'] === 'yes');
     $message->setSpamScore(isset($body['X-Mailgun-Sscore']) ? (double) $body['X-Mailgun-Sscore'] : 0);
     if (isset($body['attachments'])) {
         foreach (json_decode($body['attachments']) as $at) {
             if ($at->name == 'smime.p7s') {
                 continue;
             }
             $attachment = new Attachment();
             $attachment->setName($at->name)->setUrl(str_replace('https://', 'https://*****:*****@', $at->url));
             $message->addAttachment($attachment);
         }
     }
     return $message;
 }
Esempio n. 9
0
 /**
  * @param RequestInterface $request
  * @return ResponseInterface
  */
 public function send($request)
 {
     /**
      * var \GuzzleHttp\Message\Response $response
      */
     $headers = $request->getHeaders();
     if (!empty($this->append_headers)) {
         $headers = array_merge($headers, $this->append_headers);
     }
     $opt = [];
     if (!empty($this->basicAuth)) {
         $opt['auth'] = $this->basicAuth;
     }
     if (!empty($headers)) {
         $opt['headers'] = $headers;
     }
     $body = $request->getBody();
     if ($body !== null) {
         $opt['body'] = $body;
     }
     $g4request = $this->getClient()->createRequest($request->getMethod(), $request->getUri(), $opt);
     try {
         $response = $this->getClient()->send($g4request);
         return new Response($response->getStatusCode(), $response->getHeaders(), $response->getBody());
     } catch (\GuzzleHttp\Exception\RequestException $ex) {
         $ex_request = $ex->getRequest();
         $ex_response = $ex->getResponse();
         throw new RequestException($ex->getMessage(), $ex_request ? new Request($ex_request->getMethod(), $ex_request->getUrl(), $ex_request->getHeaders(), $ex_request->getBody()) : null, $ex_response ? new Response($ex_response->getStatusCode(), $ex_response->getHeaders(), $ex_response->getBody()) : null, $ex);
     }
 }
Esempio n. 10
0
 /**
  * {@inheritdoc}
  */
 public function request(RequestInterface $request)
 {
     $url = (string) $request->getUri();
     $body = $request->getBody();
     $body->seek(0);
     $headers = $request->getHeaders();
     $headers['Accept'] = 'application/json';
     $headers['Content-Type'] = 'application/json';
     $req = $this->guzzle->createRequest($request->getMethod(), $url);
     $req->setHeaders($headers);
     $req->setBody(GStream::factory($body->getContents()));
     try {
         $res = $this->guzzle->send($req);
     } catch (RequestException $e) {
         // Guzzle will throw exceptions for 4xx and 5xx responses, so we catch
         // them here and quietly get the response object.
         $res = $e->getResponse();
         if (!$res) {
             throw $e;
         }
     }
     $response = (new Response(new Stream('php://memory', 'w')))->withStatus($res->getStatusCode(), $res->getReasonPhrase());
     $response->getBody()->write((string) $res->getBody());
     return $response;
 }
Esempio n. 11
0
 /**
  * Assert request matches against declared specification.
  *
  * The list of constraints:
  *
  * - Assert request method defined
  * - Assert request URI declared by host, basePath, schemes and parameters (path, query)
  * - Assert content-type declared by consumes
  * - Assert headers declared by parameters (header)
  * - Assert body declared by parameters (body)
  *
  * @param Spec $spec
  * @param string $template
  * @param Request $request
  * @param string $msg
  */
 protected static final function assertRequest(Spec $spec, $template, Request $request, $msg = '')
 {
     self::assertMethodAllowed($spec, $template, $request->getMethod(), $msg);
     self::assertUri($spec, $template, $request->getMethod(), $request->getUri(), $msg);
     self::assertRequestHeaders($spec, $template, $request->getMethod(), $request->getHeaders(), $msg);
     self::assertRequestBody($spec, $template, $request->getMethod(), $request->getBody(), $msg);
 }
 function it_returns_body_with_headers(RequestInterface $request, Stream $stream)
 {
     $request->getHeaders()->shouldBeCalled()->willReturn(['content-type' => 'application/json']);
     $request->getBody()->shouldBeCalled()->willReturn($stream);
     $stream->getContents()->shouldBeCalled()->willReturn('{"data": {}}');
     $this->getBodyWithHeaders($request)->shouldReturn('content-type: application/json' . PHP_EOL . PHP_EOL . '{"data": {}}');
 }
Esempio n. 13
0
 private function addExpectHeader(RequestInterface $request, array $options, array &$modify)
 {
     // Determine if the Expect header should be used
     if ($request->hasHeader('Expect')) {
         return;
     }
     $expect = isset($options['expect']) ? $options['expect'] : null;
     // Return if disabled or if you're not using HTTP/1.1 or HTTP/2.0
     if ($expect === false || $request->getProtocolVersion() < 1.1) {
         return;
     }
     // The expect header is unconditionally enabled
     if ($expect === true) {
         $modify['set_headers']['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
     $body = $request->getBody();
     $size = $body->getSize();
     if ($size === null || $size >= (int) $expect || !$body->isSeekable()) {
         $modify['set_headers']['Expect'] = '100-Continue';
     }
 }
Esempio n. 14
0
 /**
  * @param Request $request
  *
  * @return Response
  */
 public function __invoke(Request $request)
 {
     $options = [];
     // Headers
     $headerLines = [];
     foreach ($request->getHeaders() as $name => $values) {
         $headerLines[] = sprintf('%s: %s', $name, implode(', ', $values));
     }
     $options[CURLOPT_HTTPHEADER] = $headerLines;
     // Url
     $options[CURLOPT_URL] = (string) $request->getUri();
     switch ($request->getMethod()) {
         case 'HEAD':
             $options[CURLOPT_NOBODY] = true;
             break;
         case 'GET':
             $options[CURLOPT_HTTPGET] = true;
             break;
         case 'POST':
             $options[CURLOPT_POST] = true;
             $options[CURLOPT_POSTFIELDS] = (string) $request->getBody();
             // Don't duplicate the Content-Length header
             $request = $request->withoutHeader('Content-Length');
             $request = $request->withoutHeader('Transfer-Encoding');
             break;
         case 'PUT':
             // Write to memory/temp
             $file = fopen('php://temp/' . spl_object_hash($request), 'w+');
             $bytes = fwrite($file, (string) $request->getBody());
             rewind($file);
             $options[CURLOPT_PUT] = true;
             $options[CURLOPT_INFILE] = $file;
             $options[CURLOPT_INFILESIZE] = $bytes;
             $request = $request->withoutHeader('Content-Length');
             break;
         default:
             $options[CURLOPT_CUSTOMREQUEST] = $request->getMethod();
     }
     // If the Expect header is not present, prevent curl from adding it
     if (!$request->hasHeader('Expect')) {
         $options[CURLOPT_HTTPHEADER][] = 'Expect:';
     }
     // cURL sometimes adds a content-type by default. Prevent this.
     if (!$request->hasHeader('Content-Type')) {
         $options[CURLOPT_HTTPHEADER][] = 'Content-Type:';
     }
     list($body, $headerLines) = $this->execute($options);
     $headerLines = preg_split("#\r\n#", $headerLines, -1, PREG_SPLIT_NO_EMPTY);
     $headers = [];
     // Extract the version and status from the first header
     preg_match('#HTTP/(\\d\\.\\d)\\s(\\d\\d\\d)\\s(.*)#', array_shift($headerLines), $matches);
     array_shift($matches);
     list($protocolVersion, $statusCode, $reasonPhrase) = $matches;
     foreach ($headerLines as $line) {
         list($name, $values) = preg_split('#\\s*:\\s*#', $line, 2, PREG_SPLIT_NO_EMPTY);
         $headers[$name] = preg_split('#\\s*,\\s*#', $values, -1, PREG_SPLIT_NO_EMPTY);
     }
     $response = new \GuzzleHttp\Psr7\Response($statusCode, $headers, $body, $protocolVersion, $reasonPhrase);
     return $response;
 }
Esempio n. 15
0
 protected function getPayload(RequestInterface $request)
 {
     // Calculate the request signature payload
     if ($request->hasHeader('X-Amz-Content-Sha256')) {
         // Handle streaming operations (e.g. Glacier.UploadArchive)
         return $request->getHeaderLine('X-Amz-Content-Sha256');
     }
     if (!$request->getBody()->isSeekable()) {
         throw new CouldNotCreateChecksumException('sha256');
     }
     try {
         return Psr7\hash($request->getBody(), 'sha256');
     } catch (\Exception $e) {
         throw new CouldNotCreateChecksumException('sha256', $e);
     }
 }
 /**
  * Converts a PSR request into a Guzzle request.
  *
  * @param RequestInterface $request
  *
  * @return GuzzleRequest
  */
 private function createRequest(RequestInterface $request)
 {
     $options = ['exceptions' => false, 'allow_redirects' => false];
     $options['version'] = $request->getProtocolVersion();
     $options['headers'] = $request->getHeaders();
     $options['body'] = (string) $request->getBody();
     return $this->client->createRequest($request->getMethod(), (string) $request->getUri(), $options);
 }
Esempio n. 17
0
 function it_throws_an_exception_when_no_valid_json_is_found(RequestInterface $request, StreamableInterface $body)
 {
     $body->__toString()->willReturn('INVALID');
     $body->isSeekable()->willReturn(true);
     $body->isWritable()->willReturn(true);
     $request->getBody()->willReturn($body);
     $this->shouldThrow('RuntimeException')->duringAuthenticateRequest($request);
 }
 public function assertPostBody(RequestInterface $request)
 {
     $postData = $request->getBody()->getContents();
     $this->assertEquals('POST', strtoupper($request->getMethod()));
     $this->assertContains('client_id=123', $postData);
     $this->assertContains('client_secret=328', $postData);
     $json = ['access_token' => 'asdasfaf', 'expires_in' => 15, 'token_type' => 'barear', 'scope' => 'user', 'refresh_token' => 'esd'];
     return new Response(200, [], json_encode($json));
 }
Esempio n. 19
0
 public static function request(RequestInterface $request)
 {
     $method = $request->getMethod();
     $url = $request->getUri();
     $body = $request->getBody()->getContents();
     $headers = $request->getHeaders();
     $protocolVersion = $request->getProtocolVersion();
     return new HttpObservable($method, $url, $body, $headers, $protocolVersion);
 }
 public function sign(RequestInterface $request, $key, $secret, $customerId = null)
 {
     $nonce = $this->nonceGenerator->generateNonce();
     $signature = hash_hmac('sha256', $nonce . $customerId . $key, $secret);
     parse_str($request->getBody()->getContents(), $params);
     $params = array_merge(['key' => $key, 'nonce' => $nonce, 'signature' => $signature], $params);
     $body = http_build_query($params);
     return new Request($request->getMethod(), $request->getUri(), $request->getHeaders(), $body);
 }
 public function __invoke(CommandInterface $command, RequestInterface $request)
 {
     $name = $command->getName();
     $body = $request->getBody();
     if (!$request->hasHeader('Content-MD5') && $body->getSize() && in_array($name, self::$requireMd5)) {
         $request = $request->withHeader('Content-MD5', base64_encode(Psr7\hash($body, 'md5', true)));
     }
     $next = $this->nextHandler;
     return $next($command, $request);
 }
Esempio n. 22
0
 /**
  * @inheritDoc
  */
 public function mock(RequestInterface $request)
 {
     $body = $request->getBody()->getContents();
     $bodyArray = QueryString::fromString($body);
     $post = new Post();
     $post->setId(101);
     $post->setTitle($bodyArray['title']);
     $post->setUserId($bodyArray['userId']);
     $post->setBody($bodyArray['body']);
     return new Response(200, [], SerializerBuilder::create()->build()->serialize($post, 'json'));
 }
Esempio n. 23
0
 /**
  * {@inheritDoc}
  */
 public function getContentHashedRequest(RequestInterface $request)
 {
     $body = (string) $request->getBody();
     if (!strlen($body)) {
         return clone $request;
     }
     $hashedBody = $this->digest->hash((string) $body);
     /** @var RequestInterface $request */
     $request = $request->withHeader('X-Authorization-Content-SHA256', $hashedBody);
     return $request;
 }
Esempio n. 24
0
 /**
  * @inheritDoc
  */
 public function mock(RequestInterface $request)
 {
     $json = file_get_contents(__DIR__ . '/../../Fixtures/post1.json');
     $post = SerializerBuilder::create()->build()->deserialize($json, 'Rafrsr\\SampleApi\\Model\\Post', 'json');
     $body = $request->getBody()->getContents();
     $bodyArray = QueryString::fromString($body);
     $post->setTitle($bodyArray['title']);
     $post->setUserId($bodyArray['userId']);
     $post->setBody($bodyArray['body']);
     return new Response(200, [], SerializerBuilder::create()->build()->serialize($post, 'json'));
 }
 /**
  *
  */
 protected function tickRequest()
 {
     $this->loop->futureTick(function () {
         $request = $this->setupRequest();
         $this->setupListeners($request);
         $body = $this->request->getBody()->getContents();
         $this->progress->onSending($body);
         $this->setConnectionTimeout($request);
         $request->end($body);
         $this->setRequestTimeout($request);
     });
 }
Esempio n. 26
0
 /**
  * {@inheritdoc}
  */
 public function authenticateRequest(RequestInterface $request)
 {
     $requestBody = $request->getBody();
     $this->ensureBodyRewritable($requestBody);
     $body = (string) $requestBody;
     $body = json_decode($body, true);
     $this->ensureJsonDecodedCorrectly();
     $body['email'] = $this->email;
     $body['password'] = $this->password;
     $requestBody->rewind();
     $requestBody->write(json_encode($body));
     return $request->withBody($requestBody);
 }
Esempio n. 27
0
 /**
  * Write Body of the request
  *
  * @param resource         $socket
  * @param RequestInterface $request
  * @param integer          $bufferSize
  *
  * @throws \Http\Client\Exception\NetworkException
  * @throws \Http\Client\Exception\RequestException
  */
 protected function writeBody($socket, RequestInterface $request, $bufferSize = 8192)
 {
     $body = $request->getBody();
     if ($body->isSeekable()) {
         $body->rewind();
     }
     while (!$body->eof()) {
         $buffer = $body->read($bufferSize);
         if (false === $this->fwrite($socket, $buffer)) {
             throw new NetworkException("An error occur when writing request to client (BROKEN EPIPE)", $request);
         }
     }
 }
Esempio n. 28
0
 /**
  * Serialize a request message to a string.
  *
  * @param RequestInterface $request
  * @return string
  */
 public static function toString(RequestInterface $request)
 {
     $headers = self::serializeHeaders($request->getHeaders());
     $body = (string) $request->getBody();
     $format = '%s %s HTTP/%s%s%s';
     if (!empty($headers)) {
         $headers = "\r\n" . $headers;
     }
     if (!empty($body)) {
         $headers .= "\r\n\r\n";
     }
     return sprintf($format, $request->getMethod(), $request->getRequestTarget(), $request->getProtocolVersion(), $headers, $body);
 }
Esempio n. 29
0
 /**
  * @param RequestInterface $request
  * @return ResponseInterface
  */
 public function send($request)
 {
     /**
      * var Guzzle\Http\Message\Response $response
      */
     $headers = $request->getHeaders();
     if (!empty($this->append_headers)) {
         $headers = array_merge($headers, $this->append_headers);
     }
     try {
         $g3request = $this->getClient()->createRequest($request->getMethod(), $request->getUri(), $headers, $request->getBody());
         $response = $g3request->send();
     } catch (\Guzzle\Http\Exception\BadResponseException $ex) {
         $ex_request = $ex->getRequest();
         $ex_response = $ex->getResponse();
         throw new RequestException($ex->getMessage(), $ex_request ? new Request($ex_request->getMethod(), $ex_request->getUrl(), $ex_request->getHeaders()->toArray(), $request->getBody()) : null, $ex_response ? new Response($ex_response->getStatusCode(), $ex_response->getHeaders()->toArray(), $ex_response->getBody()) : null, $ex);
     } catch (\Guzzle\Http\Exception\RequestException $ex) {
         $ex_request = $ex->getRequest();
         throw new RequestException($ex->getMessage(), $ex_request ? new Request($ex_request->getMethod(), $ex_request->getUrl(), $ex_request->getHeaders()->toArray(), $request->getBody()) : null, null, $ex);
     }
     return new Response($response->getStatusCode(), $response->getHeaderLines(), $response->getBody());
 }
 public function __invoke(CommandInterface $command, RequestInterface $request)
 {
     $next = $this->nextHandler;
     $name = $command->getName();
     $body = $request->getBody();
     if (in_array($name, self::$md5) && !$request->hasHeader('Content-MD5')) {
         // Set the content MD5 header for operations that require it.
         $request = $request->withHeader('Content-MD5', base64_encode(Psr7\hash($body, 'md5', true)));
     } elseif (in_array($name, self::$sha256) && $command['ContentSHA256']) {
         // Set the content hash header if provided in the parameters.
         $request = $request->withHeader('X-Amz-Content-Sha256', $command['ContentSHA256']);
     }
     return $next($command, $request);
 }