How can I change a Slim Request's URI path? I tried the following, however, withPath()
clones the uri thus the request object isn't changed. If it is not possible, is there a straightforward process to create a new Slim Request based on the original Request but the new URI path?
Background regarding why I wish to do so. I have a method which accepts a Slim Request, performs a cURL request to another server using Guzzle, writes to the Slim Response, and returns the Slim Response. The API which Guzzle queries almost the same path but with a version number.
$app->get('/{basetype:guids|tester}/{guid}/logs/{id:[0-9]+}', function (Request $request, Response $response, $args) {
switch($request->getQueryParam('ContentType')) {
case 'text':
//
return $this->view->render($response, 'log.html', $rs);
case 'file':
$uri=$request->getUri();
$path=$uri->getPath();
$uri->withPath(_VER_.$path);
return $this->serverBridge->proxy($request, $response, 'application/octet-stream');
}
});
class ServerBridge
{
protected $httpClient;
public function __construct(\GuzzleHttp\Client $httpClient)
{
$this->httpClient=$httpClient;
}
public function proxy(\Slim\Http\Request $slimRequest, \Slim\Http\Response $slimResponse):\Slim\Http\Response {
//$slimRequest is used to obtain data to send to Guzzle
$curlResponse = $this->httpClient->request($method, $path, $options);
//use $curlResponse to get data and write to $slimResponse
return $slimResponse;
}
}
If you change the Uri path, you have to change the request as well. This is by design. Don't worry, cloning is cheap in PHP.
<?php
$request = $request->withUri($request->getUri()->withPath('your/changed/path'));
Note: Be careful to use that new
$request
in some other calls in the middleware stack. They were made immutable for a reason. Changing the uri of a request early in the execution can have undesirable side effects.