From 76815fe664a0995f8fc66d6b180e1fa135b054be Mon Sep 17 00:00:00 2001 From: Larry Garfield Date: Fri, 27 Jul 2012 09:40:11 -0500 Subject: [PATCH] Allow the targetUrl on a redirect response to be set explicilty. --- .../HttpFoundation/RedirectResponse.php | 53 +++++++++++++------ .../Tests/RedirectResponseTest.php | 8 +++ 2 files changed, 44 insertions(+), 17 deletions(-) diff --git a/src/Symfony/Component/HttpFoundation/RedirectResponse.php b/src/Symfony/Component/HttpFoundation/RedirectResponse.php index f2e854ea9613..a9d98e6b3a90 100644 --- a/src/Symfony/Component/HttpFoundation/RedirectResponse.php +++ b/src/Symfony/Component/HttpFoundation/RedirectResponse.php @@ -39,24 +39,9 @@ public function __construct($url, $status = 302, $headers = array()) throw new \InvalidArgumentException('Cannot redirect to an empty URL.'); } - $this->targetUrl = $url; - - parent::__construct( - sprintf(' - - - - + parent::__construct('', $status, $headers); - Redirecting to %1$s - - - Redirecting to %1$s. - -', htmlspecialchars($url, ENT_QUOTES, 'UTF-8')), - $status, - array_merge($headers, array('Location' => $url)) - ); + $this->setTargetUrl($url); if (!$this->isRedirect()) { throw new \InvalidArgumentException(sprintf('The HTTP status code is not a redirect ("%s" given).', $status)); @@ -80,4 +65,38 @@ public function getTargetUrl() { return $this->targetUrl; } + + /** + * Sets the redirect target of this response. + * + * @param string $url The URL to redirect to + * + * @return RedirectResponse The current response. + */ + public function setTargetUrl($url) + { + if (empty($url)) { + throw new \InvalidArgumentException('Cannot redirect to an empty URL.'); + } + + $this->targetUrl = $url; + + $this->setContent( + sprintf(' + + + + + + Redirecting to %1$s + + + Redirecting to %1$s. + +', htmlspecialchars($url, ENT_QUOTES, 'UTF-8'))); + + $this->headers->set('Location', $url); + + return $this; + } } diff --git a/src/Symfony/Component/HttpFoundation/Tests/RedirectResponseTest.php b/src/Symfony/Component/HttpFoundation/Tests/RedirectResponseTest.php index 179ee5a3e258..b55c3b63d72c 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/RedirectResponseTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/RedirectResponseTest.php @@ -40,6 +40,14 @@ public function testGetTargetUrl() $this->assertEquals('foo.bar', $response->getTargetUrl()); } + public function testSetTargetUrl() + { + $response = new RedirectResponse('foo.bar'); + $response->setTargetUrl('baz.beep'); + + $this->assertEquals('baz.beep', $response->getTargetUrl()); + } + public function testCreate() { $response = RedirectResponse::create('foo', 301);