public function testEnsuresRequestBodyIsMasked() { $formatter = new Formatter('{req_body}'); $request = new Request('POST', 'http://foo.com?q=test'); $request->setBody(Stream::factory('<xml><creditCardType>CA</creditCardType>' . '<creditCardNumber>4564456445644564</creditCardNumber>' . '<creditCardIdentifier>123</creditCardIdentifier>' . '<creditCardExpirationMonth>01</creditCardExpirationMonth>' . '<creditCardExpirationYear>16</creditCardExpirationYear></xml>')); $this->assertEquals('<xml><creditCardType>XX</creditCardType>' . '<creditCardNumber>XXXXXXXXXXXXXXXX</creditCardNumber>' . '<creditCardIdentifier>XXX</creditCardIdentifier>' . '<creditCardExpirationMonth>XX</creditCardExpirationMonth>' . '<creditCardExpirationYear>XX</creditCardExpirationYear></xml>', $formatter->format($request)); }
public function testSetsResponseBodyForDownload() { $body = Stream::factory(); $request = new Request('GET', 'http://httbin.org'); $ee = null; $request->getEmitter()->on('headers', function (HeadersEvent $e) use(&$ee) { $ee = $e; }); $t = new Transaction(new Client(), $request); $m = new RequestMediator($t, new MessageFactory()); $m->setResponseBody($body); $this->assertEquals(18, $m->receiveResponseHeader(null, "HTTP/1.1 202 FOO\r\n")); $this->assertEquals(10, $m->receiveResponseHeader(null, "Foo: Bar\r\n")); $this->assertEquals(11, $m->receiveResponseHeader(null, "Baz : Bam\r\n")); $this->assertEquals(19, $m->receiveResponseHeader(null, "Content-Length: 3\r\n")); $this->assertEquals(2, $m->receiveResponseHeader(null, "\r\n")); $this->assertNotNull($ee); $this->assertEquals(202, $t->getResponse()->getStatusCode()); $this->assertEquals('FOO', $t->getResponse()->getReasonPhrase()); $this->assertEquals('Bar', $t->getResponse()->getHeader('Foo')); $this->assertEquals('Bam', $t->getResponse()->getHeader('Baz')); $m->writeResponseBody(null, 'foo'); $this->assertEquals('foo', (string) $body); $this->assertEquals('3', $t->getResponse()->getHeader('Content-Length')); }
/** * 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 * @param callable|null $next * @return mixed * * @throws InvalidArgumentException */ public function __invoke(Request $request, callable $next = null) { if (!$this->checkModel($next)) { throw new InvalidArgumentException('Model ' . get_class($next) . ' is not right for this method'); } $query = $request->getQuery(); $query->add('function', $this->getUriFunction()); return $next($request); }
public function testGetBody() { $request1 = $this->getRequest(); $this->assertEquals('', $request1->getBody()); $guzzleRequest = new Request('GET', 'http://example.com'); $stream = Stream::factory('test content'); $guzzleRequest->setBody($stream); $request2 = new Guzzle5($guzzleRequest); $this->assertEquals('test content', $request2->getBody()); }
/** * @test * @expectedException \PHPSC\PagSeguro\Client\PagSeguroException */ public function handleErrorShouldRaiseExceptionWhenHostIsFromPagSeguro() { $client = new Client($this->httpClient); $transaction = new Transaction($this->httpClient, $this->request); $transaction->response = $this->response; $event = new Event($transaction); $this->request->expects($this->any())->method('getHost')->willReturn(Production::WS_HOST); $this->response->expects($this->any())->method('getStatusCode')->willReturn(401); $this->response->expects($this->any())->method('getBody')->willReturn('Unauthorized'); $client->handleError($event); }
/** * @param Request $request * @return BaseResponse * * @throws RemoteCallException */ public function __invoke(Request $request) { try { $query = $request->getQuery(); $this->addParamsToUri($query); $client = new Client(); return $this->getApiResponse($client->send($request)); } catch (\Exception $e) { throw new RemoteCallException($e->getMessage()); } }
public function testAuthorizationHeader() { $plugin = $this->getPlugin(); $uri = 'http://example.com/resource/1?key=value'; $request = new Request('GET', $uri, array('Content-Type' => 'text/plain', 'Date' => 'Fri, 19 Mar 1982 00:00:04 GMT', 'Custom1' => 'Value1')); $stream = Stream::factory('test content'); $request->setBody($stream); $plugin->signRequest($request); $expected = 'Acquia 1:' . DigestVersion1Test::EXPECTED_HASH; $this->assertEquals($expected, (string) $request->getHeader('Authorization')); }
public function testKeepSignature() { $request = new Request('GET', '/endpoint?token=originalValue'); $transaction = new Transaction(new Client(), $request); $event = new BeforeEvent($transaction); $subscriber = new UrlSignature(); $subscriber->setSignatureGenerator(function () { return ['token' => 'tokenValue']; }); $subscriber->onBefore($event); $this->assertEquals('originalValue', $request->getQuery()->get('token')); }
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"; }
public function testSendsWithStreamingAdapter() { $response = new Response(200); $mock = $this->getMockBuilder('GuzzleHttp\\Adapter\\AdapterInterface')->setMethods(['send'])->getMockForAbstractClass(); $mock->expects($this->never())->method('send'); $streaming = $this->getMockBuilder('GuzzleHttp\\Adapter\\AdapterInterface')->setMethods(['send'])->getMockForAbstractClass(); $streaming->expects($this->once())->method('send')->will($this->returnValue($response)); $request = new Request('GET', '/'); $request->getConfig()->set('stream', true); $s = new StreamingProxyAdapter($mock, $streaming); $this->assertSame($response, $s->send(new Transaction(new Client(), $request))); }
/** * @param BaseMethod $method * @param BaseModel $model * @return BaseResponse * @throws InvalidArgumentException */ public function makeRequest(BaseMethod $method, BaseModel $model) { try { $request = new Request('GET', $this->_apiUrl); $query = $request->getQuery(); $query->set('user', $this->_username); $query->set('pass', $this->_password); $query->set('source', $this->_source); return $method($request, $model); } catch (\InvalidArgumentException $e) { throw new InvalidArgumentException($e->getMessage()); } }
public function testCanInterceptBeforeSending() { $client = new Client(); $request = new Request('GET', 'http://httpbin.org/get'); $response = new Response(200); $request->getEmitter()->on('before', function (BeforeEvent $e) use($response) { $e->intercept($response); }); $transaction = new Transaction($client, $request); $f = 'does_not_work'; $a = new CurlAdapter(new MessageFactory(), ['handle_factory' => $f]); $a->send($transaction); $this->assertSame($response, $transaction->getResponse()); }
/** * @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); } }
public function execute() { $body = ''; $classes = array(); $batchHttpTemplate = <<<EOF --%s Content-Type: application/http Content-Transfer-Encoding: binary MIME-Version: 1.0 Content-ID: %s %s%s %s EOF; /** @var Google_Http_Request $req */ foreach ($this->requests as $key => $request) { $firstLine = sprintf('%s %s HTTP/%s', $request->getMethod(), $request->getResource(), $request->getProtocolVersion()); $content = (string) $request->getBody(); $body .= sprintf($batchHttpTemplate, $this->boundary, $key, $firstLine, Request::getHeadersAsString($request), $content ? "\n" . $content : ''); $classes['response-' . $key] = $request->getHeader('X-Php-Expected-Class'); } $body .= "--{$this->boundary}--"; $body = trim($body); $url = Google_Client::API_BASE_PATH . '/' . self::BATCH_PATH; $headers = array('Content-Type' => sprintf('multipart/mixed; boundary=%s', $this->boundary), 'Content-Length' => strlen($body)); $request = $this->client->getHttpClient()->createRequest('POST', $url, ['headers' => $headers, 'body' => Stream::factory($body)]); $response = $this->client->getHttpClient()->send($request); return $this->parseResponse($response, $classes); }
public function testDispatchesErrorEventAndRecovers() { Server::flush(); Server::enqueue("HTTP/1.1 201 OK\r\nContent-Length: 0\r\n\r\n"); $r = new Request('GET', Server::$url); $t = new Transaction(new Client(), $r); $a = $this->getAdapter(); $r->getEmitter()->once('complete', function (CompleteEvent $e) { throw new RequestException('Foo', $e->getRequest()); }); $r->getEmitter()->on('error', function (ErrorEvent $e) { $e->intercept(new Response(200, ['Foo' => 'bar'])); }); $response = $a->send($t); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('bar', $response->getHeader('Foo')); }
/** * 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; } }
/** * @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); } }
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; }
public function testThrowsUnInterceptedErrors() { $ex = new \Exception('Foo'); $client = new Client(); $request = new Request('GET', '/'); $t = new Transaction($client, $request); $errCalled = 0; $request->getEmitter()->on('before', function (BeforeEvent $e) use($ex) { throw $ex; }); $request->getEmitter()->on('error', function (ErrorEvent $e) use(&$errCalled) { $errCalled++; }); try { RequestEvents::emitBefore($t); $this->fail('Did not throw'); } catch (RequestException $e) { $this->assertEquals(1, $errCalled); } }
public function testCreatesRingRequests() { $stream = Stream::factory('test'); $request = new Request('GET', 'http://httpbin.org/get?a=b', ['test' => 'hello'], $stream); $request->getConfig()->set('foo', 'bar'); $trans = new Transaction(new Client(), $request); $factory = new MessageFactory(); $fsm = new RequestFsm(function () { }, new MessageFactory()); $r = RingBridge::prepareRingRequest($trans, $factory, $fsm); $this->assertEquals('http', $r['scheme']); $this->assertEquals('1.1', $r['version']); $this->assertEquals('GET', $r['http_method']); $this->assertEquals('http://httpbin.org/get?a=b', $r['url']); $this->assertEquals('/get', $r['uri']); $this->assertEquals('a=b', $r['query_string']); $this->assertEquals(['Host' => ['httpbin.org'], 'test' => ['hello']], $r['headers']); $this->assertSame($stream, $r['body']); $this->assertEquals(['foo' => 'bar'], $r['client']); $this->assertFalse($r['future']); }
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']]; }
public function testProcess() { $client = $this->getClient(); $data = 'foo'; // Test data *only* uploads. $request = new Request('POST', 'http://www.example.com'); $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', $data, false); $this->assertEquals($data, (string) $request->getBody()); // Test resumable (meta data) - we want to send the metadata, not the app data. $request = new Request('POST', 'http://www.example.com'); $reqData = json_encode("hello"); $request->setBody(Stream::factory($reqData)); $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', $data, true); $this->assertEquals(json_decode($reqData), (string) $request->getBody()); // Test multipart - we are sending encoded meta data and post data $request = new Request('POST', 'http://www.example.com'); $reqData = json_encode("hello"); $request->setBody(Stream::factory($reqData)); $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', $data, false); $this->assertContains($reqData, (string) $request->getBody()); $this->assertContains(base64_encode($data), (string) $request->getBody()); }
/** * 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); }
/** * 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()); }
/** * 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()); } }
/** * @param \GuzzleHttp\Message\Request $request */ public function signRequest(Request $request) { $requestWrapper = new RequestWrapper($request); if (!$request->hasHeader('Date')) { $time = new \DateTime(); $time->setTimezone(new \DateTimeZone('GMT')); $request->setHeader('Date', $time->format('D, d M Y H:i:s \\G\\M\\T')); } if (!$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', $this->defaultContentType); } $authorization = $this->requestSigner->getAuthorization($requestWrapper, $this->id, $this->secretKey); $request->setHeader('Authorization', $authorization); }
public function execute() { $body = ''; $classes = array(); /** @var Google_Http_Request $req */ foreach ($this->requests as $key => $request) { $request->addHeaders(['Content-Type' => 'application/http', 'Content-Transfer-Encoding' => 'binary', 'MIME-Version' => '1.0', 'Content-ID' => $key]); $body .= "--{$this->boundary}"; $body .= Request::getHeadersAsString($request) . "\n\n"; $body .= sprintf('%s %s HTTP/%s', $request->getMethod(), $request->getResource(), $request->getProtocolVersion()); $body .= "\n\n"; $classes['response-' . $key] = $request->getHeader('X-Php-Expected-Class'); } $body .= "--{$this->boundary}--"; $body = trim($body); $url = Google_Client::API_BASE_PATH . '/' . self::BATCH_PATH; $headers = array('Content-Type' => sprintf('multipart/mixed; boundary=%s', $this->boundary), 'Content-Length' => strlen($body)); $request = $this->client->getHttpClient()->createRequest('POST', $url, ['headers' => $headers, 'body' => Stream::factory($body)]); $response = $this->client->getHttpClient()->send($request); return $this->parseResponse($response, $classes); }
/** * @expectedException \GuzzleHttp\Exception\AdapterException */ public function testThrowsForStreamOption() { $request = new Request('GET', Server::$url . 'haha'); $request->getConfig()->set('stream', true); $t = new Transaction(new Client(), $request); $f = new CurlFactory(); $f($t, new MessageFactory()); }
public function testThrowsAndReleasesWhenErrorDuringCompleteEvent() { Server::flush(); Server::enqueue("HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n"); $request = new Request('GET', Server::$url); $request->getEmitter()->on('complete', function (CompleteEvent $e) { throw new RequestException('foo', $e->getRequest()); }); $t = new Transaction(new Client(), $request); $a = new MultiAdapter(new MessageFactory()); try { $a->send($t); $this->fail('Did not throw'); } catch (RequestException $e) { $this->assertSame($request, $e->getRequest()); } }