redirect.php 2.32 KB
Newer Older
1 2 3 4 5
<?php namespace System;

class Redirect {

	/**
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
	 * The redirect response.
	 *
	 * @var Response
	 */
	public $response;

	/**
	 * Create a new redirect instance.
	 *
	 * @param  Response  $response
	 * @return void
	 */
	public function __construct($response)
	{
		$this->response = $response;
	}

	/**
24 25 26 27 28 29 30 31 32 33 34 35 36
	 * Create a redirect response.
	 *
	 * @param  string    $url
	 * @param  string    $method
	 * @param  int       $status
	 * @param  bool      $https
	 * @return Response
	 */
	public static function to($url, $method = 'location', $status = 302, $https = false)
	{
		$url = URL::to($url, $https);

		return ($method == 'refresh')
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
							? new static(Response::make('', $status)->header('Refresh', '0;url='.$url))
							: new static(Response::make('', $status)->header('Location', $url));
	}

	/**
	 * Add an item to the session flash data.
	 *
	 * @param  string  $key
	 * @param  mixed   $value
	 * @return Response
	 */
	public function with($key, $value)
	{
		// ----------------------------------------------------
		// Since this method uses sessions, make sure a driver
		// has been specified in the configuration file.
		// ----------------------------------------------------
		if (Config::get('session.driver') != '')
		{
			Session::flash($key, $value);
		}

		return $this;
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
	}

	/**
	 * Create a redirect response to a HTTPS URL.
	 *
	 * @param  string    $url
	 * @param  string    $method
	 * @param  int       $status
	 * @return Response
	 */
	public static function to_secure($url, $method = 'location', $status = 302)
	{
		return static::to($url, $method, $status, true);
	}

	/**
	 * Magic Method to handle redirecting to routes.
	 */
	public static function __callStatic($method, $parameters)
	{
		// ----------------------------------------------------
		// Dynamically redirect to a secure route URL.
		// ----------------------------------------------------
		if (strpos($method, 'to_secure_') === 0)
		{
			return static::to(URL::to_route(substr($method, 10), $parameters, true));
		}

		// ----------------------------------------------------
		// Dynamically redirect a route URL.
		// ----------------------------------------------------
		if (strpos($method, 'to_') === 0)
		{
			return static::to(URL::to_route(substr($method, 3), $parameters));
		}

		throw new \Exception("Method [$method] is not defined on the Redirect class.");
	}

}