Exemplo n.º 1
0
 public function formatProvider()
 {
     $request = new Request('PUT', '/', ['x-test' => 'abc'], Stream::factory('foo'));
     $response = new Response(200, ['X-Baz' => 'Bar'], Stream::factory('baz'));
     $err = new RequestException('Test', $request, $response);
     return [['{request}', [$request], (string) $request], ['{response}', [$request, $response], (string) $response], ['{request} {response}', [$request, $response], $request . ' ' . $response], ['{request} {response}', [$request], $request . ' '], ['{req_headers}', [$request], "PUT / HTTP/1.1\r\nx-test: abc"], ['{res_headers}', [$request, $response], "HTTP/1.1 200 OK\r\nX-Baz: Bar"], ['{res_headers}', [$request], 'NULL'], ['{req_body}', [$request], 'foo'], ['{res_body}', [$request, $response], 'baz'], ['{res_body}', [$request], 'NULL'], ['{method}', [$request], $request->getMethod()], ['{url}', [$request], $request->getUrl()], ['{resource}', [$request], $request->getResource()], ['{req_version}', [$request], $request->getProtocolVersion()], ['{res_version}', [$request, $response], $response->getProtocolVersion()], ['{res_version}', [$request], 'NULL'], ['{host}', [$request], $request->getHost()], ['{hostname}', [$request, $response], gethostname()], ['{hostname}{hostname}', [$request, $response], gethostname() . gethostname()], ['{code}', [$request, $response], $response->getStatusCode()], ['{code}', [$request], 'NULL'], ['{phrase}', [$request, $response], $response->getReasonPhrase()], ['{phrase}', [$request], 'NULL'], ['{error}', [$request, $response, $err], 'Test'], ['{error}', [$request], 'NULL'], ['{req_header_x-test}', [$request], 'abc'], ['{req_header_x-not}', [$request], ''], ['{res_header_X-Baz}', [$request, $response], 'Bar'], ['{res_header_x-not}', [$request, $response], ''], ['{res_header_X-Baz}', [$request], 'NULL']];
 }
Exemplo n.º 2
0
 /**
  * Create the OVH signature
  * @param Request $request
  * @param int     $time
  *
  * @return string
  */
 protected function getSignature(Request $request, $time)
 {
     $method = $request->getMethod();
     $url = $request->getUrl();
     $body = $request->getBody();
     $schema = $this->applicationSecret . '+' . $this->consumerKey . '+' . $method . '+' . $url . '+' . $body . '+' . $time;
     return '$1$' . sha1($schema);
 }
 /**
  * Send asynchronous guzzle request
  *
  * @param Psr7Request $request
  * @param \Tebru\Retrofit\Http\Callback $callback
  * @return null
  */
 public function sendAsync(Psr7Request $request, Callback $callback)
 {
     $request = new Request($request->getMethod(), (string) $request->getUri(), $request->getHeaders(), $request->getBody(), ['future' => true]);
     /** @var FutureInterface $response */
     $response = $this->client->send($request);
     $this->promises[] = $response->then(function (ResponseInterface $response) {
         return new Psr7Response($response->getStatusCode(), $response->getHeaders(), $response->getBody(), $response->getProtocolVersion(), $response->getReasonPhrase());
     })->then($callback->success(), $callback->failure());
 }
Exemplo n.º 4
0
 protected function getFileName(Request $request)
 {
     $result = trim($request->getMethod() . ' ' . $request->getResource()) . ' HTTP/' . $request->getProtocolVersion();
     foreach ($request->getHeaders() as $name => $values) {
         if (array_key_exists(strtoupper($name), $this->ignored_headers)) {
             continue;
         }
         $result .= "\r\n{$name}: " . implode(', ', $values);
     }
     $request = $result . "\r\n\r\n" . $request->getBody();
     return md5((string) $request) . ".txt";
 }
Exemplo n.º 5
0
 /**
  * Making request using Guzzle
  *
  * @param string $method Type of request, either POST, GET, PUT or DELETE
  * @param string $endpoint The operation / task for API
  * @param array $data The parameter need to be passed
  * @param array $options The options like header, body, etc
  *
  * @return EntityBodyInterface|string
  * @throws \Exception
  */
 private function sendRequest($method, $endpoint, array $data = array(), array $options = array())
 {
     $uri = $this->buildUri($endpoint);
     if ($method === "GET" || $method === "PUT") {
         $uri = $this->buildUri($endpoint, $data);
     } elseif (count($data)) {
         $options['body'] = $data;
     }
     $this->request = $this->client->createRequest($method, $uri, $options);
     $this->response = $this->client->send($this->request);
     if ($this->response->getStatusCode() >= 400) {
         $bt = debug_backtrace();
         $caller = $bt[2];
         if (isset($caller['class']) && $caller['class'] === get_class(new StacklaModel())) {
             $json = (string) $this->response->getBody();
             if (JsonValidator::validate($json, true)) {
                 $content = json_decode($json, true);
                 if (isset($content['errors'])) {
                     $caller['object']->fromArray($content);
                 }
             }
         }
         if ($this->logger) {
             $this->logger->addError('-> REQUEST [' . $this->request->getMethod() . ' - ' . $this->request->getUrl() . "]", array($this->request->getMethod() !== "GET" ? (string) $this->request->getBody() : ""));
             $this->logger->addError('<- RESPONSE [' . $this->response->getStatusCode() . ':' . $this->response->getReasonPhrase() . "]", array((string) $this->response->getBody()));
         }
     } else {
         if ($this->logger) {
             $this->logger->addInfo('-> REQUEST [' . $this->request->getMethod() . ' - ' . $this->request->getUrl() . "]", array($this->request->getMethod() !== "GET" ? (string) $this->request->getBody() : ""));
             $this->logger->addInfo('<- RESPONSE [' . $this->response->getStatusCode() . ':' . $this->response->getReasonPhrase() . "]", array($this->response->json()));
         }
     }
     $statusCode = $this->response->getStatusCode();
     switch ($statusCode) {
         case 200:
             return (string) $this->response->getBody();
         case 400:
             throw ApiException::create(sprintf("Server return %s error code. Bad request: The request could not be understood. %s", $this->response->getStatusCode(), (string) $this->response->getBody()), $statusCode, (string) $this->response->getBody());
         case 401:
             throw ApiException::create(sprintf("Server return %s error code. Unauthorized: Authentication credentials invalid or not authorised to access resource", $this->response->getStatusCode()), $statusCode, (string) $this->response->getBody());
         case 403:
             throw ApiException::create(sprintf("\n                  Server return %s error code. Rate limit exceeded: Too many requests in the current time window", $this->response->getStatusCode()), $statusCode, (string) $this->response->getBody());
         case 404:
             throw ApiException::create(sprintf("Server return %s error code. Invalid resource: Invalid resource specified or resource not found", $this->response->getStatusCode()), $statusCode, (string) $this->response->getBody());
         default:
             throw ApiException::create(sprintf("Server return %s error code.Server error: An error on the server prohibited a successful response; please contact support. %s", $this->response->getStatusCode(), (string) $this->response->getBody()), $statusCode, (string) $this->response->getBody());
     }
 }
Exemplo n.º 6
0
 /**
  * @param Request $request
  * @return array
  * @throws \Exception
  */
 public static function findMock(Request $request)
 {
     $method = strtoupper($request->getMethod());
     $type = self::getResourceTypeFromUrl($request->getUrl());
     if (!in_array($type, self::getResourceTypes())) {
         $type = self::RESOURCE_BASE;
     }
     $path = self::getPath($request->getUrl());
     $mockKey = $method . ' ' . $path;
     $mockData = (include __DIR__ . '/' . $type . '.php');
     if (isset($mockData[$mockKey])) {
         return $mockData[$mockKey];
     } else {
         throw new \Exception('Mock not found in ' . $type . '.php for request: ' . htmlentities($mockKey), 1462914673);
     }
 }
Exemplo n.º 7
0
 public function signer(Request $request)
 {
     $query = $request->getQuery();
     $query->merge($this->defaults);
     $newQuery = $query->toArray();
     if (str_contains(strtolower($request->getPath()), 'orders')) {
         $newQuery['MarketplaceId.Id.1'] = $newQuery['MarketplaceId'];
         unset($newQuery['MarketplaceId']);
     }
     ksort($newQuery, SORT_NATURAL);
     $query->replace($newQuery);
     $canonicalizedString = implode("\n", [$request->getMethod(), $request->getHost(), $request->getPath(), (string) $request->getQuery()]);
     $signature = base64_encode(hash_hmac('sha256', $canonicalizedString, env('MWS_SECRET_KEY'), true));
     $request->getQuery()->set('Signature', $signature);
     return $request;
 }
 /**
  * @param Request $request
  * @return array
  * @throws \Exception
  */
 public static function findMock(Request $request)
 {
     $method = strtoupper($request->getMethod());
     $type = self::getResourceTypeFromUrl($request->getUrl());
     //fwrite(STDERR, print_r(['type' => $type, 'method' => $method], true));
     if (!in_array($type, self::getResourceTypes())) {
         throw new \Exception('Unknown resource type found: ' . $type, 1462733299);
     }
     $path = self::getPath($request->getUrl());
     $mockKey = $method . ' ' . $path;
     $mockData = (include __DIR__ . '/' . $type . '.php');
     //fwrite(STDERR, print_r(['path' => $path, 'mockKey' => $mockKey, 'mockData' => $mockData], true));
     if (isset($mockData[$mockKey])) {
         return $mockData[$mockKey];
     } else {
         throw new \Exception('Mock not found in ' . $type . '.php for request: ' . htmlentities($mockKey), 1462914673);
     }
 }
Exemplo n.º 9
0
 public function testCanChangeMethod()
 {
     $r = new Request('GET', 'http://www.foo.com');
     $r->setMethod('put');
     $this->assertEquals('PUT', $r->getMethod());
 }
Exemplo n.º 10
0
 /**
  * {@inheritDoc}
  */
 public function getMethod()
 {
     return $this->request->getMethod();
 }
Exemplo n.º 11
0
 /**
  * Announces HTTP request to Wildfire channel
  *
  * @param GuzzleHttp\Message\Request
  * @param GuzzleHttp\Message\Response   when dealing with error events, response may not be populated
  * @param float $elapsed
  */
 public function publishRequest(Request $request, Response $response = null, $elapsed = 0)
 {
     $request_body = $request->getBody();
     $request_preview = '';
     if ($request_body) {
         $request_body->seek(0);
         // rewind the cursor in case a read was already done
         $request_preview = $request_body->read($this->_preview_length);
         $request_body->seek(0);
         // rewind the cursor, so subsequent reads are not affected
     }
     // Ensure response is populated before extracting body from it
     $response_body = $response ? $response->getBody() : '';
     $response_preview = '';
     if ($response_body) {
         $response_body->seek(0);
         // rewind the cursor, in case a read was already done
         $response_preview = $response_body->read($this->_preview_length);
         $response_body->seek(0);
         // rewind the cursor, so subsequent reads are not affected
     }
     $phrase = $response ? $response->getReasonPhrase() : self::ERROR_NO_RESPONSE;
     $table = [];
     $table[] = ['Key', 'Value'];
     $table[] = ['Phrase', $phrase];
     $table[] = ['Host', $request->getHost()];
     $table[] = ['Protocol', $request->getScheme()];
     $table[] = ['User Agent', $request->getHeader('User-Agent')];
     $table[] = ['Request', $request_preview];
     $table[] = ['Response', $response_preview];
     if ($response && $response->getEffectiveUrl() != $request->getUrl()) {
         $table[] = ['Effective URL', $response->getEffectiveUrl()];
     }
     $elapsed = number_format($elapsed, 4);
     $status = $response ? $response->getStatusCode() : 0;
     $message = sprintf("%s <%s> (%d) %s (%f)s", $this->_remote_prefix, $request->getMethod(), $status, $request->getUrl(), $elapsed);
     $this->_client->table($message, $table);
 }