route.php 2.23 KB
Newer Older
1 2
<?php namespace System\Routing;

3
use System\Package;
4
use System\Response;
5 6 7 8

class Route {

	/**
9 10 11 12 13 14 15
	 * The route key, including request method and URI.
	 *
	 * @var string
	 */
	public $key;

	/**
16 17 18 19
	 * The route callback or array.
	 *
	 * @var mixed
	 */
20
	public $callback;
21 22 23 24 25 26 27 28 29 30 31

	/**
	 * The parameters that will passed to the route function.
	 *
	 * @var array
	 */
	public $parameters;

	/**
	 * Create a new Route instance.
	 *
32 33 34
	 * @param  string  $key
	 * @param  mixed   $callback
	 * @param  array   $parameters
35 36
	 * @return void
	 */
37
	public function __construct($key, $callback, $parameters = array())
38
	{
39 40
		$this->key = $key;
		$this->callback = $callback;
41 42 43 44 45 46 47 48
		$this->parameters = $parameters;
	}

	/**
	 * Execute the route function.
	 *
	 * @param  mixed     $route
	 * @param  array     $parameters
49
	 * @return Response
50 51 52 53 54
	 */
	public function call()
	{
		$response = null;

55 56 57
		// The callback may be in array form, meaning it has attached filters or is named and we
		// will need to evaluate it further to determine what to do. If the callback is just a
		// closure, we can execute it now and return the result.
58
		if (is_callable($this->callback))
59
		{
60
			$response = call_user_func_array($this->callback, $this->parameters);
61
		}
62
		elseif (is_array($this->callback))
63
		{
64 65 66 67 68
			if (isset($this->callback['needs']))
			{
				Package::load(explode(', ', $this->callback['needs']));
			}

69
			$response = isset($this->callback['before']) ? Filter::call($this->callback['before'], array(), true) : null;
70

71
			if (is_null($response) and ! is_null($handler = $this->find_route_function()))
72
			{
73
				$response = call_user_func_array($handler, $this->parameters);
74 75 76
			}
		}

77
		$response = Response::prepare($response);
78

79
		if (is_array($this->callback) and isset($this->callback['after']))
80
		{
81
			Filter::call($this->callback['after'], array($response));
82 83 84 85 86
		}

		return $response;
	}

87 88 89
	/**
	 * Extract the route function from the route.
	 *
90 91 92
	 * If a "do" index is specified on the callback, that is the handler.
	 * Otherwise, we will return the first callable array value.
	 *
93 94
	 * @return Closure
	 */
95
	private function find_route_function()
96 97 98 99 100 101 102 103 104
	{
		if (isset($this->callback['do'])) return $this->callback['do'];

		foreach ($this->callback as $value)
		{
			if (is_callable($value)) return $value;
		}
	}

105
}