public function testToString() { $body = new StringStream(); $body->write('foobar'); $request = new Request(new Url('http://127.0.0.1'), 'POST'); $request->setHeader('Content-Type', 'text/html; charset=UTF-8'); $request->setBody($body); $httpRequest = 'POST / HTTP/1.1' . Http::$newLine; $httpRequest .= 'content-type: text/html; charset=UTF-8' . Http::$newLine; $httpRequest .= Http::$newLine; $httpRequest .= 'foobar'; $this->assertEquals($httpRequest, $request->toString()); $this->assertEquals($httpRequest, (string) $request); }
/** * Sends the request through the given handler and returns the response * * @param \PSX\Http\Request $request * @param \PSX\Http\Options $options * @param integer $count * @return \PSX\Http\Response */ public function request(Request $request, Options $options = null, $count = 0) { if (!$request->getUri()->isAbsolute()) { throw new InvalidArgumentException('Request url must be absolute'); } // set cookie headers if ($this->cookieStore !== null) { $cookies = $this->cookieStore->load($request->getUri()->getHost()); if (!empty($cookies)) { $kv = array(); foreach ($cookies as $cookie) { $path = ltrim($cookie->getPath(), '/'); if ($cookie->getExpires() !== null && $cookie->getExpires()->getTimestamp() < time()) { $this->cookieStore->remove($request->getUri()->getHost(), $cookie); } elseif ($cookie->getPath() !== null && substr($request->getUri()->getPath(), 0, strlen($path)) != $path) { // path does not fit } else { $kv[] = $cookie->getName() . '=' . $cookie->getValue(); } } $request->addHeader('Cookie', implode('; ', $kv)); } } // set content length $body = $request->getBody(); if ($body !== null && $request->hasHeader('Transfer-Encoding') != 'chunked' && !in_array($request->getMethod(), array('HEAD', 'GET'))) { $size = $body->getSize(); if ($size !== false) { $request->setHeader('Content-Length', $size); } } // set default options if ($options === null) { $options = new Options(); } // make request $response = $this->handler->request($request, $options); // store cookies if ($this->cookieStore !== null) { $cookies = $response->getHeaderLines('Set-Cookie'); foreach ($cookies as $rawCookie) { try { $cookie = new Cookie($rawCookie); $domain = $cookie->getDomain() !== null ? $cookie->getDomain() : $request->getUri()->getHost(); $this->cookieStore->store($domain, $cookie); } catch (InvalidArgumentException $e) { // invalid cookies } } } // check follow location if ($options->getFollowLocation() && ($response->getStatusCode() >= 300 && $response->getStatusCode() < 400)) { $location = (string) $response->getHeader('Location'); if (!empty($location) && $location != $request->getUri()->toString()) { if ($options->getMaxRedirects() > $count) { $location = UriResolver::resolve($request->getUri(), new Uri($location)); return $this->request(new GetRequest($location), $options, ++$count); } else { throw new RedirectException('Max redirection reached'); } } } return $response; }