config.php 2.02 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 14 15 16 17 18 19 20 21 22 23
	 * Determine if a configuration item exists.
	 *
	 * @param  string  $key
	 * @return bool
	 */
	public static function has($key)
	{
		return ! is_null(static::get($key));
	}

	/**
24 25 26
	 * Get a configuration item.
	 *
	 * @param  string  $key
27
	 * @param  string  $default
28 29
	 * @return mixed
	 */
30
	public static function get($key, $default = null)
31
	{
32
		// If no "dot" is present in the key, return the entire configuration array.
33
		if(strpos($key, '.') === false)
34 35
		{
			static::load($key);
Taylor Otwell committed
36

37
			return Arr::get(static::$items, $key, $default);
38 39 40
		}

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

42 43
		static::load($file);

44
		// Verify that the configuration file actually exists.
45
		if ( ! array_key_exists($file, static::$items))
46
		{
47
			return $default;
48 49
		}

50
		return Arr::get(static::$items[$file], $key, $default);
51 52 53 54 55 56 57 58 59
	}

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

64 65 66 67 68 69 70 71 72 73 74 75 76
		static::load($file);

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

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

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

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

	/**
90
	 * Load all of the configuration items from a file.
91 92 93 94 95 96
	 *
	 * @param  string  $file
	 * @return void
	 */
	public static function load($file)
	{
97 98
		// Bail out if already loaded or doesn't exist.
		if (array_key_exists($file, static::$items) or ! file_exists($path = APP_PATH.'config/'.$file.EXT))
99 100 101 102 103 104 105 106
		{
			return;
		}

		static::$items[$file] = require $path;
	}

}