Skip to content

Commit

Permalink
Allow the targetUrl on a redirect response to be set explicilty.
Browse files Browse the repository at this point in the history
  • Loading branch information
Crell committed Jul 27, 2012
1 parent 21d4973 commit 76815fe
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 17 deletions.
53 changes: 36 additions & 17 deletions src/Symfony/Component/HttpFoundation/RedirectResponse.php
Expand Up @@ -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('<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="1;url=%1$s" />
parent::__construct('', $status, $headers);

<title>Redirecting to %1$s</title>
</head>
<body>
Redirecting to <a href="%1$s">%1$s</a>.
</body>
</html>', 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));
Expand All @@ -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('<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="1;url=%1$s" />
<title>Redirecting to %1$s</title>
</head>
<body>
Redirecting to <a href="%1$s">%1$s</a>.
</body>
</html>', htmlspecialchars($url, ENT_QUOTES, 'UTF-8')));

$this->headers->set('Location', $url);

return $this;
}
}
Expand Up @@ -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);
Expand Down

0 comments on commit 76815fe

Please sign in to comment.