2

Say, I have an URL http://server/mysite/web/app_dev.php/resource/1. I am doing a GET request and the corresponding action is ResourceController::getAction.

In this controller action if I call $request->getPathInfo(), it gives me /resource/1.

But in the same controller if I create a Request object with a url of another resource and call getPathInfo() it returns a longer version.

$request = Request::create('http://server/mysite/web/app_dev.php/another_resource/1');
echo $request->getPathInfo();

OUTPUT >>
/mysite/web/app_dev.php/another_resource/1

How is it possible to make getPathInfo() to return only /another_resource/1 in this case?

OR

Anyone can suggest what is the safest way to convert an endpoint URL http://server/mysite/web/app_dev.php/another_resource/1 to /another_resource/1 in Symfony2?

In case you are interested to know why I need this

The controller action is receiving some URLs in request content. The action needs to parse those URLs to recognize the corresponding resource. I am trying to make use to $router->match function to retrieve the parameters from the URL. The match function expects only /another_resource/1 part.

Samiron
  • 5,169
  • 2
  • 28
  • 55
  • 1
    You can try getting the base url from your current `Request` object with `$request->getBaseUrl();` and use it with `str_replace` for instance, and replace it with an empty string with the one returned by `getPathInfo()`. This is a bit of a hacky way. I could write an answer later why you get a different output when using `::create()`. – Artamiel Sep 27 '15 at 16:37
  • Thanks @Artamaiel. This approach can definitely solve the problem as long as the baseurl doesnt change. However, I will still look for something else that will work even the base url is changed like switching to `app.php` to `app_dev.php` etc. I really want to forget about the baseurl part. Currently I am planning to put a prefix for all of the endpoints and my url parser service will split the url by that prefix. In this way i am gonna strip out the unwanted part. Not so elegant solution either but at least with this approach I dont really need worry about the `baseurl` part at all. – Samiron Sep 27 '15 at 16:57
  • `I could write an answer later why you get a different output when using ::create()`, please do. It would be certainly a useful thing to know in this context. – Samiron Sep 27 '15 at 16:59

1 Answers1

0

Request::create method create a new request that don't know any information about current request, it return full uri because it not know current script file. try:

$request = Request::create('http://server/mysite/web/app_dev.php/another_resource/1', null, array(), array(), array(), array(
    'SCRIPT_NAME' => $this->get('kernel')->getEnvironment() == 'dev' ? 'app_dev.php' : 'app.php',
    'SCRIPT_FILENAME' => $this->get('kernel')->getEnvironment() == 'dev' ? 'app_dev.php' : 'app.php',
));
echo $request->getPathInfo();
ghanbari
  • 1,630
  • 1
  • 16
  • 31