finder.php 1.64 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
<?php namespace System\Route;

class Finder {

	/**
	 * All of the loaded routes.
	 *
	 * @var array
	 */
	public static $routes;

	/**
	 * The named routes that have been found so far.
	 *
	 * @var array
	 */
	public static $names = array();

	/**
	 * Find a route by name.
	 *
	 * @param  string  $name
	 * @return array
	 */
	public static function find($name)
	{
		if (is_null(static::$routes))
		{
			static::$routes = (is_dir(APP_PATH.'routes')) ? static::load() : require APP_PATH.'routes'.EXT;
		}

		if (array_key_exists($name, static::$names))
		{
			return static::$names[$name];
		}

37 38 39 40
		// ---------------------------------------------------------
		// We haven't located the route before, so we'll need to
		// iterate through each route to find the matching name.
		// ---------------------------------------------------------
41 42 43 44 45 46 47
		$arrayIterator = new \RecursiveArrayIterator(static::$routes);
		$recursiveIterator = new \RecursiveIteratorIterator($arrayIterator);

		foreach ($recursiveIterator as $iterator)
		{
			$route = $recursiveIterator->getSubIterator();

48
			if (isset($route['name']) and $route['name'] == $name)
49 50 51 52 53 54 55 56 57
			{
				return static::$names[$name] = array($arrayIterator->key() => iterator_to_array($route));
			}
		}
	}

	/**
	 * Load all of the routes from the routes directory.
	 *
58 59 60
	 * All of the various route files will be merged together
	 * into a single array that can be searched.
	 *
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
	 * @return array
	 */
	private static function load()
	{
		$routes = array();

		foreach (glob(APP_PATH.'routes/*') as $file)
		{
			if (filetype($file) == 'file')
			{
				$routes = array_merge(require $file, $routes);
			}			
		}

		return $routes;
	}

}