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']]; }
/** * @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); } }
/** * 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); }
/** * @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); } }
/** * 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()); } }
/** * Login a user * * @param $username * @param $password * @return bool */ public function login($username, $password) { $loginUrl = sprintf('%s/site/login', trim(env('ADMIN_API_URL'), '/')); try { $request = new Request('GET', $loginUrl); $request->setQuery(['username' => $username, 'password' => $password]); $data = file_get_contents($request->getUrl()); $data = json_decode($data); if ($data->status == 'success') { $this->setAuth($data); return true; } else { return false; } } catch (\Exception $e) { return false; } }
public function testCanChangeHost() { $r = new Request('GET', 'http://www.foo.com:222'); $r->setHost('goo'); $this->assertEquals('http://goo:222', $r->getUrl()); $this->assertEquals('goo:222', $r->getHeader('host')); $r->setHost('goo:80'); $this->assertEquals('http://goo', $r->getUrl()); $this->assertEquals('goo', $r->getHeader('host')); }
/** * @param Client $client */ protected function copyClientDefaults(Client $client) { $this->request->setUrl($client->getBaseUrl() . $this->request->getUrl()); $this->request->addHeaders($client->getDefaultOption('headers')); }
/** * 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); }