/** * @covers Piccolo\Web\IO\Standard\StandardOutputProcessor */ public function testExecute() { //setup $contentBuffer = ''; $headers = []; $echo = function ($variable) use(&$contentBuffer) { $contentBuffer .= (string) $variable; }; $header = function ($string) use(&$headers) { $headers[] = (string) $string; }; /** * @var ResponseInterface $response */ $response = new Response(); $response = $response->withBody(\GuzzleHttp\Psr7\stream_for('Hello world!')); $response = $response->withHeader('X-Test-Header1', 'test'); $response = $response->withHeader('X-Test-Header2', 'test'); $output = new StandardOutputProcessor($header, $echo); //act $output->execute($response); //assert $this->assertEquals(['HTTP/1.1 200 OK', 'X-Test-Header1: test', 'X-Test-Header2: test'], $headers); $this->assertEquals('Hello world!', $contentBuffer); }
/** * {@inheritDoc} */ public function getIncomingStream() { $options = stream_context_get_options($this->context); $method = 'GET'; if (isset($options['http']['method'])) { $method = $options['http']['method']; } $headers = []; if (isset($options['http']['header'])) { $headerLines = explode("\r\n", $options['http']['header']); foreach ($headerLines as $headerLine) { list($header, $value) = explode(': ', $headerLine, 2); $headers[$header][] = $value; } } $body = null; if (isset($options['http']['content'])) { $body = $options['http']['content']; } $protocolVersion = 1.1; if (isset($options['http']['protocol_version'])) { $protocolVersion = $options['http']['protocol_version']; } $request = new Request($method, $this->path, $headers, $body, $protocolVersion); return \GuzzleHttp\Psr7\stream_for(\GuzzleHttp\Psr7\str($request)); }
/** * @return GuzzleHttp\Psr7\Stream */ public function createStreamForString($body) { return \GuzzleHttp\Psr7\stream_for($body); $stream = fopen('php://temp', 'rw'); fwrite($stream, $body); return $this->createStream($stream); }
/** * Builds PSR7 stream based on image data. Method uses Guzzle PSR7 * implementation as easiest choice. * * @param \Intervention\Image\Image $image * @return boolean */ public function execute($image) { $format = $this->argument(0)->value(); $quality = $this->argument(1)->between(0, 100)->value(); $this->setOutput(\GuzzleHttp\Psr7\stream_for($image->encode($format, $quality)->getEncoded())); return true; }
/** * {@inheritdoc} */ public function allocateStream(BucketInterface $bucket, $name) { if (!$this->exists($bucket, $name)) { throw new ServerException("Unable to create stream for '{$name}', object does not exists."); } //Getting readonly stream return \GuzzleHttp\Psr7\stream_for(fopen($this->allocateFilename($bucket, $name), 'rb')); }
/** * @param string $method * @param string $path * @param array $options * @return Response */ public function sendRequest($method, $path, array $options = []) { $url = $this->getUrl() . $path; $options['body'] = array_key_exists('body', $options) ? \GuzzleHttp\Psr7\stream_for(json_encode($options['body'])) : null; $options['headers'] = $this->headers; $guzzleResponse = $this->client->request($method, $url, $options); return new Response($guzzleResponse->getStatusCode(), (string) $guzzleResponse->getBody()); }
/** * Pretend to do a POST request * * @param $str_url * @param array $arr_params * @return \GuzzleHttp\Psr7\Response */ public function post($str_url, array $arr_params) { // echo $str_url, '::', print_r($arr_params, true), PHP_EOL; $this->str_url = $str_url; $this->arr_params = $arr_params; $obj_response = new \GuzzleHttp\Psr7\Response(); return $obj_response->withBody(\GuzzleHttp\Psr7\stream_for(json_encode($this->obj_fake_response))); }
public function __invoke(ServerRequestInterface $request, ResponseInterface $response) { if (strpos($response->getHeaderLine("Content-Type"), "application/json") == 0) { $json = json_decode($response->getBody()->getContents(), true); $response = $response->withBody(\GuzzleHttp\Psr7\stream_for($this->twig->render('layout.twig', $json))); $response = $response->withHeader("Content-Type", "text/html"); } return $response; }
/** * Creates a request. * * @param string $verb * @param string $path * @param array $parameters * * @return Request */ protected function createRequest($verb, $path, $parameters = []) { if (isset($parameters['file'])) { $this->queueResourceAs('file', \GuzzleHttp\Psr7\stream_for($parameters['file'])); unset($parameters['file']); } $request = new Request($verb, $this->getUrlFromPath($path), $this->getHeaders()); return $request->withUri($request->getUri()->withQuery(http_build_query($parameters))); }
/** * {@inheritDoc} */ public function __invoke(StreamInterface $stream) { $request = \GuzzleHttp\Psr7\parse_request($stream->getContents()); $response = $this->run($request); if ($this->getAssertionCallback()) { call_user_func($this->getAssertionCallback(), $request); } return \GuzzleHttp\Psr7\stream_for(\GuzzleHttp\Psr7\str($response)); }
public function testCreateListRequest() { $testList = ['description' => 'test description', 'title' => 'test title']; $request = ListRequestFactory::getCreateListRequest($testList); $this->assertInstanceOf('GuzzleHttp\\Psr7\\Request', $request); $this->assertEquals('POST', $request->getMethod()); $this->assertEquals('lists', $request->getUri()->getPath()); $this->assertEquals(['application/json'], $request->getHeader('Content-Type')); $this->assertEquals(\GuzzleHttp\Psr7\stream_for(json_encode($testList))->getContents(), $request->getBody()->getContents()); }
public function setUp() { parent::setUp(); $this->config = $this->app['config']['self-update']['repository_types']['github']; $this->releasesAsJson = fopen('tests/Data/releases.json', 'r'); $response = new Response(200, ['Content-Type' => 'application/json'], \GuzzleHttp\Psr7\stream_for($this->releasesAsJson)); $mock = new MockHandler([$response, $response, $response, $response]); $handler = HandlerStack::create($mock); $this->client = new Client(['handler' => $handler]); $this->client->request('GET', self::GITHUB_API_URL . '/repos/' . $this->config['repository_vendor'] . '/' . $this->config['repository_name'] . '/tags'); }
public function setUp() { // Create default HandlerStack $stack = HandlerStack::create(function (RequestInterface $request, array $options) { return new FulfilledPromise((new Response())->withBody(\GuzzleHttp\Psr7\stream_for('Hello world!'))->withHeader("Expires", gmdate('D, d M Y H:i:s T', time() + 120))); }); // Add this middleware to the top with `push` $stack->push(CacheMiddleware::getMiddleware(), 'cache'); // Initialize the client with the handler option $this->client = new Client(['handler' => $stack]); }
public function testRequest() { $response = new GuzzleHttp\Psr7\Response(200, ['X-Foo' => 'Bar'], GuzzleHttp\Psr7\stream_for('foo')); $mockedHandler = new GuzzleHttp\Handler\MockHandler([$response]); $handlerStack = \GuzzleHttp\HandlerStack::create($mockedHandler); $client = new LeagueWrap\Client(); $client->baseUrl('http://google.com'); $client->setTimeout(10); $client->addMock($handlerStack); $response = $client->request('', []); $this->assertEquals('foo', $response); }
public function testDeleteCounterOperation() { $fixtures = Operations::$deleteResponseFixtures; $token = 'test'; $response = new Response(200, [], \GuzzleHttp\Psr7\stream_for(json_encode($fixtures))); $guzzleHttpClientMock = $this->getMock('GuzzleHttp\\Client', ['request']); $guzzleHttpClientMock->expects($this->any())->method('request')->will($this->returnValue($response)); /** @var OperationsClient $mock */ $mock = $this->getMock('Yandex\\Metrica\\Management\\OperationsClient', ['getClient'], [$token]); $mock->expects($this->any())->method('getClient')->will($this->returnValue($guzzleHttpClientMock)); $result = $mock->deleteCounterOperation(1, 2); $this->assertArrayHasKey('success', $result); }
public function testStaticCreation() { $callableCalled = $assertionCallbackCalled = false; $httpEmulation = HttpEmulation::fromCallable(function () use(&$callableCalled) { $callableCalled = true; return new Response(); }, function () use(&$assertionCallbackCalled) { $assertionCallbackCalled = true; }); $request = 'GET / HTTP/1.1' . "\r\n"; $httpEmulation(\GuzzleHttp\Psr7\stream_for($request)); $this->assertTrue($callableCalled); $this->assertTrue($assertionCallbackCalled); }
/** * Requests for an access token. * * @param Client $client * @param string $subdomain * @param array $params * * @return array * @throws ApiResponseException */ public static function getAccessToken(Client $client, $subdomain, array $params, $domain = 'zendesk.com') { $authUrl = "https://{$subdomain}.{$domain}/oauth/tokens"; // Fetch access_token $params = array_merge(['code' => null, 'client_id' => null, 'client_secret' => null, 'grant_type' => 'authorization_code', 'scope' => 'read write', 'redirect_uri' => null], $params); try { $request = new Request('POST', $authUrl, ['Content-Type' => 'application/json']); $request = $request->withBody(\GuzzleHttp\Psr7\stream_for(json_encode($params))); $response = $client->send($request); } catch (RequestException $e) { throw new ApiResponseException($e); } return json_decode($response->getBody()->getContents()); }
/** * @param $saveToPath * @param bool $overwriteExistingFile * @param bool $flush * @return \SplFileInfo * @throws \InvalidArgumentException */ public function createFileStream($saveToPath, $overwriteExistingFile = true, $flush = true) { $saveDir = pathinfo($saveToPath, PATHINFO_DIRNAME); if (!is_dir($saveDir) || !is_writable($saveDir) || $overwriteExistingFile && file_exists($saveToPath)) { throw new \InvalidArgumentException("The path to save the file to is not writable"); } $mode = $overwriteExistingFile ? 'w+' : 'x+'; $fileStream = \GuzzleHttp\Psr7\stream_for(fopen($saveToPath, $mode)); $this->rewind(); \GuzzleHttp\Psr7\copy_to_stream($this->stream, $fileStream); if ($flush) { $this->close(); } return $fileStream; }
/** * {@inheritdoc} */ public function upload(RequestInterface $request) { $this->headerParser->reset(); $uri = $request->getUri(); $ch = curl_init((string) $uri); $options = $this->optionsGenerator->generate($request); curl_setopt_array($ch, $options); $body = curl_exec($ch); if (0 !== curl_errno($ch)) { throw new SpeechKitException(curl_error($ch), curl_errno($ch)); } list($status, $reason) = $this->headerParser->getStatusInfo(); $headers = $this->headerParser->getHeaders(); $body = \GuzzleHttp\Psr7\stream_for($body); return new Response($status, $headers, $body, '1.1', $reason); }
public function testGetKeywords() { $jsonFile = dirname($GLOBALS['configurationFilePath']) . '/' . $GLOBALS['GOOGLE_KW_RESPONSE_JSON_FILE']; if (!file_exists($jsonFile)) { die("Could not found json response for parse"); } $response = new \GuzzleHttp\Psr7\Response(200, [], \GuzzleHttp\Psr7\stream_for(fopen($jsonFile, 'r'))); $kwResponse = new Response($response); $keywords = $kwResponse->getKeywords(); $this->assertEquals(1483, count($keywords)); foreach ($keywords as $keyword) { $this->assertEquals(['kw', 'vol'], array_keys($keyword)); $this->assertInternalType('int', $keyword['vol']); $this->assertInternalType('string', $keyword['kw']); $this->assertNotEmpty($keyword['kw']); } }
/** * @param int $expectedCode * @param null|string $fixtureFile * @return MockHandler */ public function createResponseMock($expectedCode, $fixtureFile = null) { if ($expectedCode >= 400 || $expectedCode >= 500) { $response = new Response(); $response = $response->withStatus($expectedCode); $request = new Request('GET', '/'); $responseMock = new RequestException("", $request, $response); } else { $responseMock = new Response(); $responseMock = $responseMock->withStatus($expectedCode); $responseMock = $responseMock->withHeader('Location', uniqid()); if (!empty($fixtureFile)) { $fixture = file_get_contents($fixtureFile); $responseMock = $responseMock->withBody(\GuzzleHttp\Psr7\stream_for($fixture)); } } return new MockHandler([$responseMock]); }
function testGetCategoryModels() { $json = file_get_contents(__DIR__ . '/' . $this->fixturesFolder . '/popular-category-models.json'); $jsonObj = json_decode($json); $response = new Response(200, [], \GuzzleHttp\Psr7\stream_for($json)); $popularClientMock = $this->getMock('Yandex\\Market\\Content\\Clients\\PopularClient', ['sendRequest']); $popularClientMock->expects($this->any())->method('sendRequest')->will($this->returnValue($response)); $popularModels = $popularClientMock->getCategoryModels(90402, ['geo_id' => 44]); $categories = $popularModels->getCategories(); /** @var Category $category0 */ $category0 = $categories->current(); $this->assertEquals($jsonObj->popular->topCategoryList[0]->id, $category0->getId()); $this->assertEquals($jsonObj->popular->topCategoryList[0]->name, $category0->getName()); $categoryVendor = $category0->getVendors(); /** @var Vendor $vendor0 */ $vendor0 = $categoryVendor->current(); $this->assertEquals($jsonObj->popular->topCategoryList[0]->topVendors[0]->id, $vendor0->getId()); $this->assertEquals($jsonObj->popular->topCategoryList[0]->topVendors[0]->name, $vendor0->getName()); $this->assertEquals($jsonObj->popular->topCategoryList[0]->topVendors[0]->topModelId, $vendor0->getModelId()); $this->assertEquals($jsonObj->popular->topCategoryList[0]->topVendors[0]->topModelImage, $vendor0->getModelPhotoUrl()); /** @var Vendor $vendor1 */ $vendor1 = $categoryVendor->next(); $this->assertEquals($jsonObj->popular->topCategoryList[0]->topVendors[1]->id, $vendor1->getId()); $this->assertEquals($jsonObj->popular->topCategoryList[0]->topVendors[1]->name, $vendor1->getName()); $this->assertEquals($jsonObj->popular->topCategoryList[0]->topVendors[1]->topModelId, $vendor1->getModelId()); $this->assertEquals($jsonObj->popular->topCategoryList[0]->topVendors[1]->topModelImage, $vendor1->getModelPhotoUrl()); /** @var Category $category1 */ $category1 = $categories->next(); $this->assertEquals($jsonObj->popular->topCategoryList[1]->id, $category1->getId()); $this->assertEquals($jsonObj->popular->topCategoryList[1]->name, $category1->getName()); $categoryVendor = $category1->getVendors(); /** @var Vendor $vendor0 */ $vendor0 = $categoryVendor->current(); $this->assertEquals($jsonObj->popular->topCategoryList[1]->topVendors[0]->id, $vendor0->getId()); $this->assertEquals($jsonObj->popular->topCategoryList[1]->topVendors[0]->name, $vendor0->getName()); $this->assertEquals($jsonObj->popular->topCategoryList[1]->topVendors[0]->topModelId, $vendor0->getModelId()); $this->assertEquals($jsonObj->popular->topCategoryList[1]->topVendors[0]->topModelImage, $vendor0->getModelPhotoUrl()); /** @var Vendor $vendor1 */ $vendor1 = $categoryVendor->next(); $this->assertEquals($jsonObj->popular->topCategoryList[1]->topVendors[1]->id, $vendor1->getId()); $this->assertEquals($jsonObj->popular->topCategoryList[1]->topVendors[1]->name, $vendor1->getName()); $this->assertEquals($jsonObj->popular->topCategoryList[1]->topVendors[1]->topModelId, $vendor1->getModelId()); $this->assertEquals($jsonObj->popular->topCategoryList[1]->topVendors[1]->topModelImage, $vendor1->getModelPhotoUrl()); }
function testGetFilteredResponse() { $json = file_get_contents(__DIR__ . '/' . $this->fixturesFolder . '/get-database-snapshot-filtered.json'); $jsonObj = json_decode($json); $response = new Response(200, [], \GuzzleHttp\Psr7\stream_for($json)); /** @var DataSyncClient $dataSyncClientMock */ $dataSyncClientMock = $this->getMock('Yandex\\DataSync\\DataSyncClient', ['sendRequest']); $dataSyncClientMock->expects($this->any())->method('sendRequest')->will($this->returnValue($response)); $databaseId = 'test'; $context = DataSyncClient::CONTEXT_USER; $collectionId = 'my_schedule'; $fields = ['revision', 'size']; /** @var DatabaseSnapshotResponse $snapshotResponse */ $snapshotResponse = $dataSyncClientMock->getDatabaseSnapshot($databaseId, $context, $collectionId, $fields); //Response $this->assertEquals($jsonObj->revision, $snapshotResponse->getRevision()); $this->assertEquals($jsonObj->size, $snapshotResponse->getSize()); $this->assertEmpty($snapshotResponse->getDatabaseId()); }
public function testArrayHeaderAccess() { $stream = StreamWrapper::getResource(\GuzzleHttp\Psr7\stream_for('')); $httpEmulator = new HttpEmulator('http://example.com', $stream); $response = 'HTTP/1.1 200 OK' . "\r\n"; $response .= 'Content-Type: application/json' . "\r\n"; $response .= "\r\n"; $response .= 'test123'; $httpEmulator->setResponseStream(\GuzzleHttp\Psr7\stream_for($response)); $this->assertTrue(isset($httpEmulator['headers'])); $this->assertInternalType('array', $httpEmulator['headers']); $this->assertCount(2, $httpEmulator['headers']); $this->assertEquals('HTTP/1.1 200 OK', $httpEmulator['headers'][0]); $this->assertEquals('Content-Type: application/json', $httpEmulator['headers'][1]); unset($httpEmulator['headers']); $this->assertTrue(isset($httpEmulator['headers'])); $httpEmulator['headers'] = []; $this->assertCount(2, $httpEmulator['headers']); }
/** * Use the send method to call every endpoint except for oauth/tokens * * @param HttpClient $client * @param string $endPoint E.g. "/tickets.json" * @param array $options * Available options are listed below: * array $queryParams Array of unencoded key-value pairs, e.g. ["ids" => "1,2,3,4"] * array $postFields Array of unencoded key-value pairs, e.g. ["filename" => "blah.png"] * string $method "GET", "POST", etc. Default is GET. * string $contentType Default is "application/json" * * @return \stdClass | null The response body, parsed from JSON into an object. Also returns null if something went wrong * @throws ApiResponseException * @throws AuthException */ public static function send(HttpClient $client, $endPoint, $options = []) { $options = array_merge(['method' => 'GET', 'contentType' => 'application/json', 'postFields' => null, 'queryParams' => null], $options); $headers = array_merge(['Accept' => 'application/json', 'Content-Type' => $options['contentType'], 'User-Agent' => $client->getUserAgent()], $client->getHeaders()); $request = new Request($options['method'], $client->getApiUrl() . $client->getApiBasePath() . $endPoint, $headers); $requestOptions = []; if (!empty($options['multipart'])) { $request = $request->withoutHeader('Content-Type'); $requestOptions['multipart'] = $options['multipart']; } elseif (!empty($options['postFields'])) { $request = $request->withBody(\GuzzleHttp\Psr7\stream_for(json_encode($options['postFields']))); } elseif (!empty($options['file'])) { if (is_file($options['file'])) { $fileStream = new LazyOpenStream($options['file'], 'r'); $request = $request->withBody($fileStream); } } if (!empty($options['queryParams'])) { foreach ($options['queryParams'] as $queryKey => $queryValue) { $uri = $request->getUri(); $uri = $uri->withQueryValue($uri, $queryKey, $queryValue); $request = $request->withUri($uri, true); } } // \RockstarGames\Cake\Log\Log::debug($request); // \RockstarGames\Cake\Log\Log::debug($options); try { list($request, $requestOptions) = $client->getAuth()->prepareRequest($request, $requestOptions); $response = $client->guzzle->send($request, $requestOptions); } catch (RequestException $e) { $requestException = RequestException::create($e->getRequest(), $e->getResponse()); throw new ApiResponseException($requestException); } finally { $client->setDebug($request->getHeaders(), $request->getBody()->getContents(), isset($response) ? $response->getStatusCode() : null, isset($response) ? $response->getHeaders() : null, isset($e) ? $e : null); $request->getBody()->rewind(); } if (isset($file)) { fclose($file); } $client->setSideload(null); return json_decode($response->getBody()->getContents()); }
/** * @inheritDoc */ public function mock(RequestInterface $request) { list($action, $data) = QPayXMLParser::parseRequest($request->getBody()->getContents()); try { $responseData = $this->mockService($data); } catch (\RuntimeException $e) { return new Response(500, [], \GuzzleHttp\Psr7\stream_for($e->getMessage())); } catch (\Exception $e) { $responseData = ['Header' => ['a:Error' => ['a:ErrorCode' => $e->getCode() ?: 99, 'a:ErrorMessage' => $e->getTraceAsString()]]]; } if (!$responseData) { throw new \Exception(sprintf('Invalid mock response for %s', $action)); } if (is_array($responseData)) { $response = QPayXMLParser::createResponse($action, $responseData); } else { $response = $responseData; } return new Response(200, [], \GuzzleHttp\Psr7\stream_for($response)); }
public function testUpload() { $client = new Client(['base_uri' => 'http://127.0.0.1:8000/']); $filePath = __DIR__ . '/Resources/image.jpg'; $fileSha1Checksum = sha1_file($filePath); $fileResource = fopen($filePath, 'r'); $fileStream = \GuzzleHttp\Psr7\stream_for($fileResource); $uploadResponse = $client->request('POST', '/storage/upload', ['body' => $fileStream]); $this->assertEquals(201, $uploadResponse->getStatusCode()); $body = $uploadResponse->getBody(); $bodyArray = json_decode($body, true); $this->assertArrayHasKey('fileId', $bodyArray); $fileId = $bodyArray['fileId']; $downloadResponse = $client->request('GET', '/storage/download', ['body' => json_encode(['fileId' => $fileId])]); $downloadFilePath = '/tmp/downloadTestFile'; $downloadFileResource = fopen($downloadFilePath, 'w+'); stream_copy_to_stream($downloadResponse->getBody()->detach(), $downloadFileResource); $downloadFileSha1Checksum = sha1_file($downloadFilePath); $this->assertEquals($fileSha1Checksum, $downloadFileSha1Checksum); }
/** * Send request upstream * * @param Request $request * * @return Response * @throws HttpException */ public static function makeRequest(Request $request) { try { $url = Url::createFromUrl($request->fullUrl()); $host = static::getHostFromUrl($url); $client = new Client(['base_uri' => $url->getScheme() . '://' . $host]); $proxyRequest = new GuzzleRequest($request->method(), $request->path()); $headers = $request->header(); array_walk($headers, function ($value, $key) use($proxyRequest) { $proxyRequest->withHeader($key, $value); }); $stream = \GuzzleHttp\Psr7\stream_for(json_encode($request->json()->all())); $response = $client->send($proxyRequest, ['timeout' => 2, 'body' => $stream, 'query' => $request->query(), 'form_params' => $request->input()]); return static::createLocalResponse($response); } catch (Exception $e) { if (get_class($e) == GuzzleException\ClientException::class) { return static::createLocalResponse($e->getResponse()); } abort(404); } }
public function testRequest() { $response = new GuzzleHttp\Psr7\Response(200, ['X-Foo' => 'Bar'], GuzzleHttp\Psr7\stream_for('foo')); $mockedHandler = new GuzzleHttp\Handler\MockHandler([$response]); $handlerStack = \GuzzleHttp\HandlerStack::create($mockedHandler); $client = new LeagueWrap\Client(); $client->baseUrl('http://google.com'); $client->setTimeout(10); $client->addMock($handlerStack); $response = $client->request('', []); $this->assertEquals('foo', $response); $this->assertEquals(200, $response->getCode()); $this->assertTrue($response->hasHeader('X-Foo')); $this->assertFalse($response->hasHeader('Missing-Header')); $this->assertEquals('Bar', $response->getHeader('X-Foo')); $this->assertNull($response->getHeader('that does not exists')); $headers = $response->getHeaders(); $this->assertArrayHasKey('X-Foo', $headers); $this->assertCount(1, $headers); $this->assertEquals('Bar', $headers['X-Foo']); }
/** * @param RequestInterface $request * * @return ResponseInterface */ public function send(RequestInterface $request) { $headers = $request->getHeaders(); $body = $request->getBody(); $method = $request->getMethod(); $uri = $request->getUri(); $this->client->setHeaders($headers); if ($method == 'GET') { $this->client->get($uri); } if ($method == 'POST') { $contents = (string) $body; $this->client->post($uri, $contents); } $response = new Response(); $headers = $this->client->getHeaders(); foreach ($headers as $header => $value) { $response = $response->withHeader($header, $value); } $response = $response->withBody(\GuzzleHttp\Psr7\stream_for($this->client->getBody())); $response = $response->withStatus($this->client->getStatus()); return $response; }