/**
* Forward the request to the target url and return the response.
*
* @param string $target
* @throws UnexpectedValueException
* @return Response
*/
public function to($target)
{
if (is_null($this->request)) {
throw new UnexpectedValueException('Missing request instance.');
}
$target = new Uri($target);
// Overwrite target scheme and host.
$uri = $this->request->getUri()->withScheme($target->getScheme())->withHost($target->getHost());
// Check for custom port.
if ($port = $target->getPort()) {
$uri = $uri->withPort($port);
}
// Check for subdirectory.
if ($path = $target->getPath()) {
$uri = $uri->withPath(rtrim($path, '/') . '/' . ltrim($uri->getPath(), '/'));
}
$request = $this->request->withUri($uri);
$stack = $this->filters;
$stack[] = function (RequestInterface $request, ResponseInterface $response, callable $next) {
$response = $this->adapter->send($request);
return $next($request, $response);
};
$relay = (new RelayBuilder())->newInstance($stack);
return $relay($request, new Response());
}