Files
spa-api/system/config.php

109 lines
2.2 KiB
PHP
Raw Normal View History

2011-06-08 23:45:08 -05:00
<?php namespace System;
class Config {
/**
* All of the loaded configuration items.
*
* @var array
*/
private static $items = array();
/**
2011-07-07 23:16:52 -05:00
* Determine if a configuration item or file exists.
*
* @param string $key
* @return bool
*/
public static function has($key)
{
return ! is_null(static::get($key));
}
2011-06-08 23:45:08 -05:00
/**
* Get a configuration item.
*
2011-07-07 23:16:52 -05:00
* 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.
*
2011-06-08 23:45:08 -05:00
* @param string $key
* @param string $default
2011-07-07 23:16:52 -05:00
* @return array
2011-06-08 23:45:08 -05:00
*/
public static function get($key, $default = null)
2011-06-08 23:45:08 -05:00
{
2011-07-07 23:16:52 -05:00
if (strpos($key, '.') === false)
{
static::load($key);
2011-06-16 22:45:33 -05:00
return Arr::get(static::$items, $key, $default);
}
list($file, $key) = static::parse($key);
2011-06-16 22:45:33 -05:00
2011-06-08 23:45:08 -05:00
static::load($file);
if ( ! array_key_exists($file, static::$items))
2011-06-16 20:21:23 -05:00
{
2011-07-06 14:37:59 -07:00
return is_callable($default) ? call_user_func($default) : $default;
2011-06-16 20:21:23 -05:00
}
return Arr::get(static::$items[$file], $key, $default);
2011-06-08 23:45:08 -05:00
}
/**
* Set a configuration item.
*
* @param string $key
* @param mixed $value
* @return void
*/
2011-06-10 12:19:19 -07:00
public static function set($key, $value)
2011-06-08 23:45:08 -05:00
{
list($file, $key) = static::parse($key);
2011-06-16 22:45:33 -05:00
2011-06-08 23:45:08 -05:00
static::load($file);
static::$items[$file][$key] = $value;
}
/**
* Parse a configuration key.
*
2011-07-07 23:16:52 -05:00
* 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.
*
2011-06-08 23:45:08 -05:00
* @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)));
}
/**
* Load all of the configuration items from a file.
2011-06-08 23:45:08 -05:00
*
* @param string $file
* @return void
*/
public static function load($file)
{
2011-07-07 23:16:52 -05:00
if ( ! array_key_exists($file, static::$items) and file_exists($path = APP_PATH.'config/'.$file.EXT))
2011-06-08 23:45:08 -05:00
{
2011-07-07 23:16:52 -05:00
static::$items[$file] = require $path;
2011-06-08 23:45:08 -05:00
}
}
}