public function testCastsToString() { $m = new Request('GET', 'http://foo.com'); $m->setHeader('foo', 'bar'); $m->setBody(Stream::factory('baz')); $this->assertEquals("GET / HTTP/1.1\r\nHost: foo.com\r\nfoo: bar\r\n\r\nbaz", (string) $m); }
public function testCastsToString() { $r = new Request('GET', 'http://test.com/test', ['foo' => 'baz'], Stream::factory('body')); $s = explode("\r\n", (string) $r); $this->assertEquals("GET /test HTTP/1.1", $s[0]); $this->assertContains('Host: test.com', $s); $this->assertContains('foo: baz', $s); $this->assertContains('', $s); $this->assertContains('body', $s); }
/** * Prepares the contents of a POST file. * * @param mixed $content Content of the POST file */ private function prepareContent($content) { $this->content = $content; if (!$this->content instanceof StreamInterface) { $this->content = Stream::factory($this->content); } elseif ($this->content instanceof MultipartBody) { if (!$this->hasHeader('Content-Disposition')) { $disposition = 'form-data; name="' . $this->name . '"'; $this->headers['Content-Disposition'] = $disposition; } if (!$this->hasHeader('Content-Type')) { $this->headers['Content-Type'] = sprintf("multipart/form-data; boundary=%s", $this->content->getBoundary()); } } }
/** * Create the aggregate stream that will be used to upload the POST data */ protected function createStream(array $fields, array $files) { $stream = new AppendStream(); foreach ($fields as $name => $fieldValues) { foreach ((array) $fieldValues as $value) { $stream->addStream(Stream::factory($this->getFieldString($name, $value))); } } foreach ($files as $file) { if (!$file instanceof PostFileInterface) { throw new \InvalidArgumentException('All POST fields must ' . 'implement PostFieldInterface'); } $stream->addStream(Stream::factory($this->getFileHeaders($file))); $stream->addStream($file->getContent()); $stream->addStream(Stream::factory("\r\n")); } // Add the trailing boundary with CRLF $stream->addStream(Stream::factory("--{$this->boundary}--\r\n")); return $stream; }
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 testCanAddHeaders() { $p = new PostFile('foo', Stream::factory('hi'), 'test.php', ['X-Foo' => '123', 'Content-Disposition' => 'bar']); $this->assertEquals('bar', $p->getHeaders()['Content-Disposition']); $this->assertEquals('123', $p->getHeaders()['X-Foo']); }
public function testSaveToFile() { $filename = sys_get_temp_dir() . '/mock_test_' . uniqid(); $file = tmpfile(); $stream = new Stream(tmpfile()); $m = new Mock([new Response(200, [], Stream::factory('TEST FILENAME')), new Response(200, [], Stream::factory('TEST FILE')), new Response(200, [], Stream::factory('TEST STREAM'))]); $client = new Client(); $client->getEmitter()->attach($m); $client->get('/', ['save_to' => $filename]); $client->get('/', ['save_to' => $file]); $client->get('/', ['save_to' => $stream]); $this->assertFileExists($filename); $this->assertEquals('TEST FILENAME', file_get_contents($filename)); $meta = stream_get_meta_data($file); $this->assertFileExists($meta['uri']); $this->assertEquals('TEST FILE', file_get_contents($meta['uri'])); $this->assertFileExists($stream->getMetadata('uri')); $this->assertEquals('TEST STREAM', file_get_contents($stream->getMetadata('uri'))); unlink($filename); }
protected function applyOptions(RequestInterface $request, array $options = []) { $config = $request->getConfig(); $emitter = $request->getEmitter(); foreach ($options as $key => $value) { if (isset(self::$configMap[$key])) { $config[$key] = $value; continue; } switch ($key) { case 'allow_redirects': if ($value === false) { continue; } if ($value === true) { $value = self::$defaultRedirect; } elseif (!is_array($value)) { throw new Iae('allow_redirects must be true, false, or array'); } else { // Merge the default settings with the provided settings $value += self::$defaultRedirect; } $config['redirect'] = $value; $emitter->attach($this->redirectPlugin); break; case 'decode_content': if ($value === false) { continue; } $config['decode_content'] = true; if ($value !== true) { $request->setHeader('Accept-Encoding', $value); } break; case 'headers': if (!is_array($value)) { throw new Iae('header value must be an array'); } foreach ($value as $k => $v) { $request->setHeader($k, $v); } break; case 'exceptions': if ($value === true) { $emitter->attach($this->errorPlugin); } break; case 'body': if (is_array($value)) { $this->addPostData($request, $value); } elseif ($value !== null) { $request->setBody(Stream::factory($value)); } break; case 'auth': if (!$value) { continue; } if (is_array($value)) { $type = isset($value[2]) ? strtolower($value[2]) : 'basic'; } else { $type = strtolower($value); } $config['auth'] = $value; if ($type == 'basic') { $request->setHeader('Authorization', 'Basic ' . base64_encode("{$value['0']}:{$value['1']}")); } elseif ($type == 'digest') { // @todo: Do not rely on curl $config->setPath('curl/' . CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); $config->setPath('curl/' . CURLOPT_USERPWD, "{$value['0']}:{$value['1']}"); } break; case 'query': if ($value instanceof Query) { $original = $request->getQuery(); // Do not overwrite existing query string variables by // overwriting the object with the query string data passed // in the URL $value->overwriteWith($original->toArray()); $request->setQuery($value); } elseif (is_array($value)) { // Do not overwrite existing query string variables $query = $request->getQuery(); foreach ($value as $k => $v) { if (!isset($query[$k])) { $query[$k] = $v; } } } else { throw new Iae('query must be an array or Query object'); } break; case 'cookies': if ($value === true) { static $cookie = null; if (!$cookie) { $cookie = new Cookie(); } $emitter->attach($cookie); } elseif (is_array($value)) { $emitter->attach(new Cookie(CookieJar::fromArray($value, $request->getHost()))); } elseif ($value instanceof CookieJarInterface) { $emitter->attach(new Cookie($value)); } elseif ($value !== false) { throw new Iae('cookies must be an array, true, or CookieJarInterface'); } break; case 'events': if (!is_array($value)) { throw new Iae('events must be an array'); } $this->attachListeners($request, $this->prepareListeners($value, ['before', 'complete', 'error', 'progress', 'end'])); break; case 'subscribers': if (!is_array($value)) { throw new Iae('subscribers must be an array'); } foreach ($value as $subscribers) { $emitter->attach($subscribers); } break; case 'json': $request->setBody(Stream::factory(json_encode($value))); if (!$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', 'application/json'); } break; default: // Check for custom handler functions. if (isset($this->customOptions[$key])) { $fn = $this->customOptions[$key]; $fn($request, $value); continue; } throw new Iae("No method can handle the {$key} config key"); } } }
public function testCanCastToString() { $client = new Client(['base_url' => 'http://localhost/']); $h = new History(); $client->getEmitter()->attach($h); $mock = new Mock(array(new Response(301, array('Location' => '/redirect1', 'Content-Length' => 0)), new Response(307, array('Location' => '/redirect2', 'Content-Length' => 0)), new Response(200, array('Content-Length' => '2'), Stream::factory('HI')))); $client->getEmitter()->attach($mock); $request = $client->createRequest('GET', '/'); $client->send($request); $this->assertEquals(3, count($h)); $h = str_replace("\r", '', $h); $this->assertContains("> GET / HTTP/1.1\nHost: localhost\nUser-Agent:", $h); $this->assertContains("< HTTP/1.1 301 Moved Permanently\nLocation: /redirect1", $h); $this->assertContains("< HTTP/1.1 307 Temporary Redirect\nLocation: /redirect2", $h); $this->assertContains("< HTTP/1.1 200 OK\nContent-Length: 2\n\nHI", $h); }
public function testCanChangeSaveToLocation() { $saveTo = Stream::factory(); $request = (new MessageFactory())->createRequest('GET', '/', ['save_to' => $saveTo]); $this->assertSame($saveTo, $request->getConfig()->get('save_to')); }
public function testPreventsComplexExternalEntities() { $xml = '<?xml version="1.0"?><!DOCTYPE scan[<!ENTITY test SYSTEM "php://filter/read=convert.base64-encode/resource=ResponseTest.php">]><scan>&test;</scan>'; $response = new Response(200, [], Stream::factory($xml)); $oldCwd = getcwd(); chdir(__DIR__); try { $xml = $response->xml(); chdir($oldCwd); $this->markTestIncomplete('Did not throw the expected exception! XML resolved as: ' . $xml->asXML()); } catch (\Exception $e) { chdir($oldCwd); } }
/** * Creates a Guzzle request object using a ring request array. * * @param array $request Ring request * * @return Request * @throws \InvalidArgumentException for incomplete requests. */ public static function fromRingRequest(array $request) { $options = []; if (isset($request['version'])) { $options['protocol_version'] = $request['version']; } if (!isset($request['http_method'])) { throw new \InvalidArgumentException('No http_method'); } return new Request($request['http_method'], Core::url($request), isset($request['headers']) ? $request['headers'] : [], isset($request['body']) ? Stream::factory($request['body']) : null, $options); }
public function testProxiesSetters() { $str = Stream::factory('foo'); $response = new Response(200, ['Foo' => 'bar'], $str); $future = MockTest::createFuture(function () use($response) { return $response; }); $future->setStatusCode(202); $this->assertEquals(202, $future->getStatusCode()); $this->assertEquals(202, $response->getStatusCode()); $future->setReasonPhrase('foo'); $this->assertEquals('foo', $future->getReasonPhrase()); $this->assertEquals('foo', $response->getReasonPhrase()); }
/** * Creates an application/x-www-form-urlencoded stream body * * @return StreamInterface */ private function createUrlEncoded() { return Stream::factory($this->getFields(true)); }
public function testUsesProvidedContentLengthAndRemovesXferEncoding() { $s = new Prepare(); $t = $this->getTrans(); $t->request->setBody(Stream::factory('foo')); $t->request->setHeader('Content-Length', '3'); $t->request->setHeader('Transfer-Encoding', 'chunked'); $s->onBefore(new BeforeEvent($t)); $this->assertEquals(3, $t->request->getHeader('Content-Length')); $this->assertFalse($t->request->hasHeader('Transfer-Encoding')); }