config.php 2.49 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<?php namespace System;

class Config {

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

	/**
	 * Get a configuration item.
	 *
	 * @param  string  $key
	 * @return mixed
	 */
	public static function get($key)
	{
20
		// -----------------------------------------------------
21 22
		// If a dot is not present, we will just return the
		// entire configuration array.
23
		// -----------------------------------------------------
24
		if(strpos($key, '.') === false)
25 26
		{
			static::load($key);
Taylor Otwell committed
27

28 29 30 31
			return static::$items[$key];
		}

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

33 34
		static::load($file);

35 36 37 38 39 40
		if (array_key_exists($key, static::$items[$file]))
		{
			return static::$items[$file][$key];
		}

		throw new \Exception("Configuration item [$key] is not defined.");
41 42 43 44 45 46 47 48 49
	}

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

54 55 56 57 58 59 60 61 62 63 64 65 66
		static::load($file);

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

	/**
	 * Parse a configuration key.
	 *
	 * @param  string  $key
	 * @return array
	 */
	private static function parse($key)
	{
67 68 69 70 71 72 73 74
		// -----------------------------------------------------
		// 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.
		//
		// This syntax allows for the easy retrieval and setting
		// of configuration items.
		// -----------------------------------------------------
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
		$segments = explode('.', $key);

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

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

	/**
	 * Load all of the configuration items.
	 *
	 * @param  string  $file
	 * @return void
	 */
	public static function load($file)
	{
93 94 95
		// -----------------------------------------------------
		// If we have already loaded the file, bail out.
		// -----------------------------------------------------
96 97 98 99 100 101 102 103 104 105
		if (array_key_exists($file, static::$items))
		{
			return;
		}

		if ( ! file_exists($path = APP_PATH.'config/'.$file.EXT))
		{
			throw new \Exception("Configuration file [$file] does not exist.");
		}

106 107 108 109
		// -----------------------------------------------------
		// Load the configuration array into the array of items.
		// The items array is keyed by filename.
		// -----------------------------------------------------
110 111 112 113
		static::$items[$file] = require $path;
	}

}