RedirectResponse.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation;
  11. /**
  12. * RedirectResponse represents an HTTP response doing a redirect.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. *
  16. * @api
  17. */
  18. class RedirectResponse extends Response
  19. {
  20. protected $targetUrl;
  21. /**
  22. * Creates a redirect response so that it conforms to the rules defined for a redirect status code.
  23. *
  24. * @param string $url The URL to redirect to
  25. * @param integer $status The status code (302 by default)
  26. * @param array $headers The headers (Location is always set to the given url)
  27. *
  28. * @see http://tools.ietf.org/html/rfc2616#section-10.3
  29. *
  30. * @api
  31. */
  32. public function __construct($url, $status = 302, $headers = array())
  33. {
  34. if (empty($url)) {
  35. throw new \InvalidArgumentException('Cannot redirect to an empty URL.');
  36. }
  37. $this->targetUrl = $url;
  38. parent::__construct(
  39. sprintf('<!DOCTYPE html>
  40. <html>
  41. <head>
  42. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  43. <meta http-equiv="refresh" content="1;url=%1$s" />
  44. <title>Redirecting to %1$s</title>
  45. </head>
  46. <body>
  47. Redirecting to <a href="%1$s">%1$s</a>.
  48. </body>
  49. </html>', htmlspecialchars($url, ENT_QUOTES, 'UTF-8')),
  50. $status,
  51. array_merge($headers, array('Location' => $url))
  52. );
  53. if (!$this->isRedirect()) {
  54. throw new \InvalidArgumentException(sprintf('The HTTP status code is not a redirect ("%s" given).', $status));
  55. }
  56. }
  57. /**
  58. * {@inheritDoc}
  59. */
  60. static public function create($url = '', $status = 302, $headers = array())
  61. {
  62. return new static($url, $status, $headers);
  63. }
  64. /**
  65. * Returns the target URL.
  66. *
  67. * @return string target URL
  68. */
  69. public function getTargetUrl()
  70. {
  71. return $this->targetUrl;
  72. }
  73. }