public function __construct($environment, $output, $input, $headers) { $this->stdOut = Psr7\stream_for($output); $this->environment = $environment; list($protocolName, $protocolVersion) = explode('/', $environment['SERVER_PROTOCOL']); $this->request = new Psr7\Request($environment['REQUEST_METHOD'], $environment['REQUEST_SCHEME'] . '://' . $environment['HTTP_HOST'] . $environment['REQUEST_URI'], $headers, $input, $protocolVersion); }
/** * @param string $uri * @param string $method * @param array $data * @param array $query_params * @param string $resource * @param string $action * @return mixed * @throws StreamFeedException */ public function makeHttpRequest($uri, $method, $data = [], $query_params = [], $resource = '', $action = '') { $query_params['api_key'] = $this->api_key; $client = $this->getHttpClient(); $headers = $this->getHttpRequestHeaders($resource, $action); $Uri = new Psr7\Uri($this->client->buildRequestUrl($uri)); $Uri = $Uri->withQuery(http_build_query($query_params)); $request = new Request($method, $Uri, $headers, null, $this->guzzleOptions); if ($method === 'POST' || $method === 'POST') { $json_data = json_encode($data); $request = $request->withBody(Psr7\stream_for($json_data)); } try { $response = $client->send($request); } catch (Exception $e) { if ($e instanceof ClientException) { throw new StreamFeedException($e->getResponse()->getBody()); } else { throw $e; } } $body = $response->getBody()->getContents(); $json_body = json_decode($body, true); return $json_body; }
/** * @param mixed $value A binary value compatible with Guzzle streams. * * @see GuzzleHttp\Stream\Stream::factory */ public function __construct($value) { if (!is_string($value)) { $value = Psr7\stream_for($value); } $this->value = (string) $value; }
public function testPUT() { $request = new Request('PUT', 'http://local.example', [], Psr7\stream_for('foo=bar&hello=world')); $curl = $this->curlFormatter->format($request); $this->assertContains("-d 'foo=bar&hello=world'", $curl); $this->assertContains('-X PUT', $curl); }
public function testInflatesStreamsWithFilename() { $content = $this->getGzipStringWithFilename('test'); $a = Psr7\stream_for($content); $b = new InflateStream($a); $this->assertEquals('test', (string) $b); }
public function testInflatesStreams() { $content = gzencode('test'); $a = Psr7\stream_for($content); $b = new InflateStream($a); $this->assertEquals('test', (string) $b); }
public function testHasStream() { $s = Psr7\stream_for('foo'); $e = new SeekException($s, 10); $this->assertSame($s, $e->getStream()); $this->assertContains('10', $e->getMessage()); }
public function valueProvider() { $fh = fopen('php://temp', 'r+'); fwrite($fh, $this->value); rewind($fh); return [[$this->value], [$fh], [Psr7\stream_for($this->value)]]; }
/** * @expectedException \RuntimeException * @expectedExceptionMessage Cannot write to a non-writable stream */ public function testHandlesClose() { $s = Psr7\stream_for('foo'); $wrapped = new NoSeekStream($s); $wrapped->close(); $wrapped->write('foo'); }
public function test_it_builds_http_errors() { $request = new Request('POST', '/servers'); $response = new Response(400, [], stream_for('Invalid parameters')); $requestStr = trim($this->builder->str($request)); $responseStr = trim($this->builder->str($response)); $errorMessage = <<<EOT HTTP Error ~~~~~~~~~~ The remote server returned a "400 Bad Request" error for the following transaction: Request ~~~~~~~ {$requestStr} Response ~~~~~~~~ {$responseStr} Further information ~~~~~~~~~~~~~~~~~~~ Please ensure that your input values are valid and well-formed. Visit http://docs.php-opencloud.com/en/latest/http-codes for more information about debugging HTTP status codes, or file a support issue on https://github.com/php-opencloud/openstack/issues. EOT; $e = new BadResponseError($errorMessage); $e->setRequest($request); $e->setResponse($response); $this->assertEquals($e, $this->builder->httpError($request, $response)); }
public function formatProvider() { $request = new Request('PUT', '/', ['x-test' => 'abc'], Psr7\stream_for('foo')); $response = new Response(200, ['X-Baz' => 'Bar'], Psr7\stream_for('baz')); $err = new RequestException('Test', $request, $response); return [['{request}', [$request], Psr7\str($request)], ['{response}', [$request, $response], Psr7\str($response)], ['{request} {response}', [$request, $response], Psr7\str($request) . ' ' . Psr7\str($response)], ['{request} {response}', [$request], Psr7\str($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->getUri()], ['{target}', [$request], $request->getRequestTarget()], ['{req_version}', [$request], $request->getProtocolVersion()], ['{res_version}', [$request, $response], $response->getProtocolVersion()], ['{res_version}', [$request], 'NULL'], ['{host}', [$request], $request->getHeaderLine('Host')], ['{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 static final function onDeletedResource($response) { $data = (array) json_decode($response->getBody(), true); Arr::forget($data, ['code', 'message']); $data = json_encode($data); return $response->withBody(Psr7\stream_for($data)); }
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); $request = $media->getRequest(); $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 = $request->withBody(Psr7\stream_for($reqData)); $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', $data, true); $request = $media->getRequest(); $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 = $request->withBody(Psr7\stream_for($reqData)); $media = new Google_Http_MediaFileUpload($client, $request, 'image/png', $data, false); $request = $media->getRequest(); $this->assertContains($reqData, (string) $request->getBody()); $this->assertContains(base64_encode($data), (string) $request->getBody()); }
/** * Specter JSON Fake Data * * The route should return json data of Specter format, and this middleware * will substitute fake data into it. * * @param RequestInterface $request PSR7 request * @param ResponseInterface $response PSR7 response * @param callable $next Next middleware * * @return ResponseInterface * @throws InvalidArgumentException * @throws LogicException */ public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) { /** * We are a post processor, and so we run the $next immediately * * @var ResponseInterface $response */ $response = $next($request, $response); // Decode the json returned by the route and prepare it for mock data // processing. $fixture = @json_decode($response->getBody()->getContents(), true); if (json_last_error() !== JSON_ERROR_NONE) { throw new LogicException('Failed to parse json string. Error: ' . json_last_error_msg()); } // We will not process files without the Specter trigger, and instead // return an unchanged response. if (!array_key_exists($this->specterTrigger, $fixture)) { return $response; } // Process the fixture data, using a seed in case the designer wants // a repeatable result. $seed = $request->getHeader('SpecterSeed'); $specter = new Specter(array_shift($seed)); $json = $specter->substituteMockData($fixture); // Prepare a fresh body stream $data = json_encode($json); $stream = Psr7\stream_for($data); // Return an immutable body in a cloned $request object return $response->withBody($stream); }
/** * {@inheritdoc} */ public function createStream($body = null) : StreamInterface { try { return stream_for($body); } catch (Exception $exception) { throw new DomainException($exception->getMessage(), $exception->getCode(), $exception); } }
public function __doRequest($request, array $headers = array()) { $this->headers = $headers; $this->emit('before.request', array(&$request, &$headers)); $xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . '<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:enc="http://www.w3.org/2003/05/soap-encoding">' . '<soap:Body xmlns:rpc="http://www.w3.org/2003/05/soap-rpc">' . '<TestResponse>' . '<foo>foo</foo>' . '<bar>bar</bar>' . '</TestResponse>' . '</soap:Body>' . '</soap:Envelope>'; $stream = Psr7\stream_for($xml); return new HttpResponse(200, array(), $stream); }
public function saveToFile($path) { $resource = fopen($path, 'w'); /* @var $fileStream \GuzzleHttp\Psr7\Stream */ $fileStream = Psr7\stream_for($resource); $fileStream->write($this->getByte()); fclose($resource); }
private function authenticateRequest(HttpRequest $request) { $body = JsonRpc\json_decode((string) $request->getBody()->getContents(), true); $body['auth'] = $this->auth_token; $json_body = JsonRpc\json_encode($body); $request = $request->withBody(Psr7\stream_for($json_body)); return $request; }
public function testShouldReturnTokenInfo() { $wantedTokens = ['access_token' => '1/abdef1234567890', 'expires_in' => '57', 'token_type' => 'Bearer']; $jsonTokens = json_encode($wantedTokens); $httpHandler = getHandler([buildResponse(200, [GCECredentials::FLAVOR_HEADER => 'Google']), buildResponse(200, [], Psr7\stream_for($jsonTokens))]); $g = new GCECredentials(); $this->assertEquals($wantedTokens, $g->fetchAuthToken($httpHandler)); }
/** * Test reverse, ok */ public function testReverseOk() { $client = new NominatimClient(); $mock = new MockHandler([new Response(200, [], Psr7\stream_for('ABC'))]); $client->getGuzzleClient()->getConfig('handler')->setHandler($mock); $response = $client->reverse(0.01, 0.01); $this->assertEquals('ABC', $response->getBody()->getContents()); }
public function setUp() { $this->c = fopen('php://temp', 'r+'); fwrite($this->c, 'foo'); fseek($this->c, 0); $this->a = Psr7\stream_for($this->c); $this->b = new Str($this->a); }
/** * Converts default GET request to a POST request * * Avoiding length restriction in query * * @param RequestInterface $r GET request to be converted * @return RequestInterface $req converted POST request */ public static function convertGetToPost(RequestInterface $r) { if ($r->getMethod() === 'POST') { return $r; } $query = $r->getUri()->getQuery(); $req = $r->withMethod('POST')->withBody(Psr7\stream_for($query))->withHeader('Content-Length', strlen($query))->withHeader('Content-Type', 'application/x-www-form-urlencoded')->withUri($r->getUri()->withQuery('')); return $req; }
public function testClose() { $dest = __DIR__ . '/closeTest.gz'; $fh = fopen($dest, 'w'); $a = Psr7\stream_for($fh); $gzStream = new GzStreamGuzzle($a); $content = 'The quick brown fox jumps over the lazy dog'; $gzStream->write($content); }
public function testUploadsObjectFromStream() { $stream = Psr7\stream_for('somedata'); $options = ['name' => uniqid(self::TESTING_PREFIX)]; $object = self::$bucket->upload($stream, $options); self::$deletionQueue[] = $object; $this->assertEquals($options['name'], $object->name()); $this->assertEquals($stream->getSize(), $object->info()['size']); }
/** * @scenario An exception is thrown when a deferred result cannot be obtained after a configured number of attempts * * @expectedException RuntimeException */ public function testGetDeferredResultMaxAttemptsReached() { $client = new Client('someone', 'some_secret', 'http://www.whatever.com'); $client->setDeferredResultInterval(0); $client->setDeferredResultMaxAttempts(2); $mock = new MockHandler([new Response(202, [], Psr7\stream_for('First attempt')), new Response(202, [], Psr7\stream_for('Second attempt')), new Response(202, [], Psr7\stream_for('Third attempt')), new Response(200, [], Psr7\stream_for('Finally!'))]); $client->getGuzzleClient()->getConfig('handler')->setHandler($mock); $response = $client->get('some_path', []); $content = $response->getBody()->getContents(); }
/** * @param RequestWrapper $requestWrapper * @param string|resource|StreamInterface $data * @param string $uri * @param array $options [optional] { * Optional configuration. * * @type array $metadata Metadata on the resource. * @type int $chunkSize Size of the chunks to send incrementally during * a resumable upload. Must be in multiples of 262144 bytes. * @type array $httpOptions HTTP client specific configuration options. * @type int $retries Number of retries for a failed request. * **Defaults to** `3`. * @type string $contentType Content type of the resource. * } */ public function __construct(RequestWrapper $requestWrapper, $data, $uri, array $options = []) { $this->requestWrapper = $requestWrapper; $this->data = Psr7\stream_for($data); $this->uri = $uri; $this->metadata = isset($options['metadata']) ? $options['metadata'] : []; $this->chunkSize = isset($options['chunkSize']) ? $options['chunkSize'] : null; $this->requestOptions = array_intersect_key($options, ['httpOptions' => null, 'retries' => null]); $this->contentType = isset($options['contentType']) ? $options['contentType'] : 'application/octet-stream'; }
/** @test if we can put an object from a stream and then get it */ public function canPutObjectFromStreamAnAndGetIt() { $actualObject = "I'm a stream..."; $stream = Psr7\stream_for($actualObject); $objectPath = sprintf('%s/%s.txt', self::$testDir, (string) Uuid::uuid4()); $putResponse = self::$instance->putObject($stream, $objectPath); $this->assertNotNull($putResponse->getHeaders(), "Object not inserted: {$objectPath}"); $objectContents = self::$instance->getObjectAsString($objectPath); $this->assertEquals($actualObject, $objectContents, "Remote object data is not equal to data stored"); }
public function testUploadsData() { $requestWrapper = $this->prophesize('Google\\Cloud\\RequestWrapper'); $stream = Psr7\stream_for('abcd'); $successBody = '{"canI":"kickIt"}'; $response = new Response(200, [], $successBody); $requestWrapper->send(Argument::type('Psr\\Http\\Message\\RequestInterface'), Argument::type('array'))->willReturn($response); $uploader = new MultipartUploader($requestWrapper->reveal(), $stream, 'http://www.example.com'); $this->assertEquals(json_decode($successBody, true), $uploader->upload()); }
public function testGetClientError() { $MOCK_RESPONSE = new Response(400, ['Content-Type' => 'application/json; charset=UTF-8'], Psr7\stream_for(fopen(__DIR__ . '/mocks/rest_client_400_Bad_Request.txt', 'r'))); $client = new RESTAdapter\RESTClient('https://api.instagram.com', new MockHandler([$MOCK_RESPONSE])); $INVALID_URI = '/v1/location/614396723'; $QUERY = ['access_token' => 'accessToken123']; $HEADERS = ['Accept' => 'application/json']; $response_body = $client->get($INVALID_URI, $QUERY, $HEADERS); $this->assertEquals($MOCK_RESPONSE->getStatusCode(), 400); $this->assertEquals($MOCK_RESPONSE->getBody(), $response_body->getBody()); }
/** * @param Response|RequestException|string $response * @param string $language */ protected function mockResponse($response, $language = 'en') { $this->api(); if (is_string($response)) { $this->mock->append(new Response(200, ['Content-Type' => 'application/json; charset=utf-8', 'Content-Language' => $language], Psr7\stream_for($response))); } elseif ($response instanceof RequestException) { $this->mock->append($response); } else { $this->mock->append($response); } }