Code: Select all
<?php
/**
* Static app configuration to use anywhere
* @package XXXX
* @author XXXX
*/
class Config
{
/**
* Various config value from INI file
* @var array config
*/
private static $directives = array();
/**
* Load the INI file and parse it
* @param string path
*/
public static function load($file)
{
if (file_exists($file)) self::$directives = parse_ini_file($file);
}
/**
* Check if a given directive exists
* @param stirng key
* @return bool
*/
public static function has($key)
{
return array_key_exists($key, self::$directives);
}
/**
* Get the value for $key, return null if not set
* @param string key
* @return mixed
*/
public static function get($key)
{
if (self::has($key))
{
return self::$directives[$key];
}
}
/**
* Set a new directive or override an existing one
* @param string key
* @param mixed value
*/
public static function set($key, $value)
{
self::$directives[$key] = $value;
}
/**
* Remove a config directive if set
* @param string key
*/
public static function delete($key)
{
if (self::has($key))
{
self::$directives[$key] = null; //Saves memory since unset() doesn't free this up
unset(self::$directives[$key]);
}
}
/**
* Clear out all config directives
*/
public static function flush()
{
self::$directives = array();
}
/**
* Write the configuration as-is into a file
* @param string path
* @return bool
*/
public static function save($path)
{
$content = '';
$sections = '';
foreach (self::$directives as $key => $item)
{
if (is_array($item))
{
$sections .= "\n[{$key}]\n";
foreach ($item as $key2 => $item2)
{
if (is_numeric($item2) || is_bool($item2)) $sections .= "{$key2} = {$item2}\n";
else $sections .= "{$key2} = \"{$item2}\"\n";
}
}
else
{
if(is_numeric($item) || is_bool($item)) $content .= "{$key} = {$item}\n";
else $content .= "{$key} = \"{$item}\"\n";
}
}
$content .= $sections;
if (!$handle = fopen($path, 'w+')) return false;
if (!fwrite($handle, $content)) return false;
fclose($handle);
return true;
}
}