config.php 2.24 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
<?php namespace System;

class Config {

	/**
	 * All of the loaded configuration items.
	 *
	 * @var array
	 */
	private static $items = array();

	/**
13
	 * Determine if a configuration item or file exists.
14 15 16 17 18 19 20 21 22 23
	 *
	 * @param  string  $key
	 * @return bool
	 */
	public static function has($key)
	{
		return ! is_null(static::get($key));
	}

	/**
24 25
	 * Get a configuration item.
	 *
26 27 28 29 30 31 32
	 * Configuration items are retrieved using "dot" notation. So, asking for the
	 * "application.timezone" configuration item would return the "timezone" option
	 * from the "application" configuration file.
	 *
	 * If the name of a configuration file is passed without specifying an item, the
	 * entire configuration array will be returned.
	 *
33
	 * @param  string  $key
34
	 * @param  string  $default
35
	 * @return array
36
	 */
37
	public static function get($key, $default = null)
38
	{
39
		if (strpos($key, '.') === false)
40 41
		{
			static::load($key);
Taylor Otwell committed
42

43
			return Arr::get(static::$items, $key, $default);
44 45 46
		}

		list($file, $key) = static::parse($key);
Taylor Otwell committed
47

48 49
		static::load($file);

50
		if ( ! array_key_exists($file, static::$items))
51
		{
52
			return is_callable($default) ? call_user_func($default) : $default;
53 54
		}

55
		return Arr::get(static::$items[$file], $key, $default);
56 57 58 59 60 61 62 63 64
	}

	/**
	 * Set a configuration item.
	 *
	 * @param  string  $key
	 * @param  mixed   $value
	 * @return void
	 */
65
	public static function set($key, $value)
66 67
	{
		list($file, $key) = static::parse($key);
Taylor Otwell committed
68

69 70 71 72 73 74 75 76
		static::load($file);

		static::$items[$file][$key] = $value;
	}

	/**
	 * Parse a configuration key.
	 *
77 78 79
	 * The value on the left side of the dot is the configuration file
	 * name, while the right side of the dot is the item within that file.
	 *
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
	 * @param  string  $key
	 * @return array
	 */
	private static function parse($key)
	{
		$segments = explode('.', $key);

		if (count($segments) < 2)
		{
			throw new \Exception("Invalid configuration key [$key].");
		}

		return array($segments[0], implode('.', array_slice($segments, 1)));
	}

	/**
96
	 * Load all of the configuration items from a file.
97 98 99 100 101 102
	 *
	 * @param  string  $file
	 * @return void
	 */
	public static function load($file)
	{
103
		if ( ! array_key_exists($file, static::$items) and file_exists($path = APP_PATH.'config/'.$file.EXT))
104
		{
105
			static::$items[$file] = require $path;
106 107 108 109
		}
	}

}