From 16cb504d8e66a16ce6a734dbc77fc567f9284d96 Mon Sep 17 00:00:00 2001 From: Will Rossiter Date: Fri, 29 Jun 2012 22:02:30 +1200 Subject: [PATCH] API: add $includeGetVars flag for SS_HTTPRequest() to return the URL with the attached GET parameters. --- control/HTTPRequest.php | 24 ++++++++++++++++++++++-- tests/control/HTTPRequestTest.php | 12 ++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/control/HTTPRequest.php b/control/HTTPRequest.php index c26baf6cf..59c8a5875 100644 --- a/control/HTTPRequest.php +++ b/control/HTTPRequest.php @@ -228,10 +228,30 @@ class SS_HTTPRequest implements ArrayAccess { } /** + * Returns the URL used to generate the page + * + * @param bool $includeGetVars whether or not to include the get parameters\ + * * @return string */ - function getURL() { - return ($this->getExtension()) ? $this->url . '.' . $this->getExtension() : $this->url; + function getURL($includeGetVars = false) { + $url = ($this->getExtension()) ? $this->url . '.' . $this->getExtension() : $this->url; + + if ($includeGetVars) { + // if we don't unset $vars['url'] we end up with /my/url?url=my/url&foo=bar etc + + $vars = $this->getVars(); + unset($vars['url']); + + if (count($vars)) { + $url .= '?' . http_build_query($vars); + } + } + else if(strpos($url, "?") !== false) { + $url = substr($url, 0, strpos($url, "?")); + } + + return $url; } /** diff --git a/tests/control/HTTPRequestTest.php b/tests/control/HTTPRequestTest.php index fa92643f1..4214904c8 100644 --- a/tests/control/HTTPRequestTest.php +++ b/tests/control/HTTPRequestTest.php @@ -242,4 +242,16 @@ class HTTPRequestTest extends SapphireTest { $req->addHeader('X-Requested-With', 'XMLHttpRequest'); $this->assertTrue($req->isAjax()); } + + public function testGetURL() { + $req = new SS_HTTPRequest('GET', '/'); + $this->assertEquals('', $req->getURL()); + + $req = new SS_HTTPRequest('GET', '/assets/somefile.gif'); + $this->assertEquals('assets/somefile.gif', $req->getURL()); + + $req = new SS_HTTPRequest('GET', '/home?test=1'); + $this->assertEquals('home?test=1', $req->getURL(true)); + $this->assertEquals('home', $req->getURL()); + } }