/lib/config/cfConfig.class.php
PHP | 508 lines | 314 code | 18 blank | 176 comment | 11 complexity | 724ab5854b80b7bbba05697c97ca071e MD5 | raw file
Possible License(s): LGPL-3.0
- <?php
- /**
- -----------------------------------------------------------------------------
- * CONFIG MANAGEMENT
- *
- * Read one or more config files an put the settings into defined categories.
- * Your application can take the settings via static method getEntry().
- *
- * Only files with the defined file types defined by the registered config readers will be read. (Default are .php and .ini)
- * The settings from the files will be stored in the designated category defined by the filename itself.
- * e.g.: database.ini will be stored in the category "database"
- *
- *
- * Example:
- * 1. cfConfig::addIncludePath('full qualified path to your config files');
- * 2. cfConfig::scanIncludePath() ... scan the includes and read all defined config files defined by the registered config readers.
- * 3. cfConfig::getEntry('mySetting', 'Categoryname'); e.g: cfConfig::getEntry('hostname', 'database');
- *
- -----------------------------------------------------------------------------
- -----------------------------------------------------------------------------
- * @copyright (C) 2011 Cyberfox Software Solutions e.U.
- * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License version 3 (LGPLv3)
- * @author Christian Graf <christian.graf@cyberfox.at>
- -----------------------------------------------------------------------------
- -----------------------------------------------------------------------------
- * @package redfox
- * @subpackage dataset
- * @category data
- -----------------------------------------------------------------------------
- -----------------------------------------------------------------------------
- * @version $Id: cfConfig.class.php 89 2012-05-22 11:19:33Z cgraf $
- * @date $Date: 2012-05-22 13:19:33 +0200 (Di, 22 Mai 2012) $
- * @svnauthor $Author: cgraf $
- -----------------------------------------------------------------------------
- */
- class cfConfig
- {
- /**
- * Stores the config setting data.
- * array('category' => array(settings))
- *
- * @var array
- * @access private
- * @static
- */
- private static $data = null;
- /**
- * Associated array of defined categories.
- * array('categoryname' => 'description')
- *
- * @var array
- * @access private
- * @static
- */
- private static $categories = array();
- /**
- * Name of the default categorie. Uses if the assigment of settings could not be taken.
- * Default name is "misc".
- *
- * @var string
- * @access private
- * @static
- */
- private static $defaultCategory = 'misc';
- /**
- * List of full qualified file path to the config files.
- *
- * @var array
- * @access private
- * @static
- */
- private static $include_path = array();
- /**
- * List of registered config readers. (Classnames)
- *
- * @var array
- * @access private
- * @static
- */
- private static $configReaders = array();
- /**
- * GetAllCategories()
- *
- * Returns an associated array of all defined categories.
- * array('categoryname' => 'description')
- *
- * If not categories defined, the follow predefined list will be returned:
- * 1. 'core' => 'Framework Settings',
- * 2. 'database' => 'Database Connectivity Settings',
- * 3. 'session' => 'Session Managment Settings',
- * 4. 'error' => 'Error Management Settings',
- * 5. 'template' => 'Template Settings',
- * 6. 'application' => 'Application Settings',
- * 7. 'misc' => 'All other stuff, also default'
- *
- * @return array An associated array of all defined categories
- * @access public
- * @final
- * @static
- */
- public static function GetAllCategories()
- {
- if(empty(self::$categories))
- {
- self::$categories = array(
- 'core' => 'Framework Settings',
- 'database' => 'Database Connectivity Settings',
- 'session' => 'Session Managment Settings',
- 'error' => 'Error Management Settings',
- 'template' => 'Template Settings',
- 'application' => 'Application Settings',
- '_application_state' => 'Dynamic Application Settings made by the application itselfs',
- 'misc' => 'All other stuff, also default'
- );
- }
- return self::$categories;
- }
- /**
- * getDefaultCategory()
- *
- * Returns the name of the default category. Default is "misc".
- *
- * @return string The name of the default category
- * @access public
- * @final
- * @static
- */
- final public static function GetDefaultCategory()
- {
- return self::$defaultCategory;
- }
- /**
- * GetDataObject()
- *
- * Returns the data object array.
- * Each category has it's own cfDataObject to store the settings.
- * array('categoryname' => cfDataObject)
- *
- * @return array Array of data objects
- * @access protected
- * @final
- * @static
- */
- final protected static function &GetData()
- {
- if(is_null(self::$data))
- {
- $categories = self::GetAllCategories();
- self::$data = array();
- foreach(array_keys($categories) as $categ)
- {
- self::$data[$categ] = array();
- }
- }
- return self::$data;
- }
- /**
- * SetEntry()
- *
- * Set one setting-entry to a category.
- *
- * @param string $Name Name of the setting
- * @param mixed $Value Value of the setting
- * @param string $Category (optional) Name of the selected category, if it is empty the defualt category will be taken.
- * @return void
- * @access public
- * @final
- * @static
- */
- final public static function SetEntry($Name, $Value, $Category = null)
- {
- if(empty($Category))
- $Category = self::GetDefaultCategory();
- $data =& self::GetData();
- if(!isset($data[$Category]))
- $data[$Category] = array();
- $data[$Category][$Name] = $Value;
- }
- /**
- * IsEntrySet()
- *
- * Checks if an entry has been set.
- *
- * @param string $Name Name of the setting
- * @param string $Category (optional) Name of the selected category, if it is empty the defualt category will be taken.
- * @return bool TRUE if an entry has been set
- * @access public
- * @final
- * @static
- */
- final public static function IsEntrySet($Name, $Category = null)
- {
- if(empty($Category))
- $Category = self::GetDefaultCategory();
- $data =& self::GetData();
- return isset($data[$Category][$Name]);
- }
- /**
- * GetEntry()
- *
- * Returns the value of an setting entry
- *
- * @param string $Name Name of the setting
- * @param string $Category (optional) Name of the selected category, if it is empty the defualt category will be taken.
- * @return mixed The value of the designated setting entry. Returns NULL if no setting available.
- * @access public
- * @final
- * @static
- */
- final public static function GetEntry($Name, $Category = null)
- {
- if(empty($Category))
- $Category = self::GetDefaultCategory();
- $data =& self::GetData();
- if(isset($data[$Category][$Name]))
- {
- return $data[$Category][$Name];
- }
- return null;
- }
- /**
- * GetAllEntries()
- *
- * Returns an associated array of all settings which have been set in a category
- * array('setting' => value)
- * or
- * array('category' => array('setting' => value))
- *
- * @param string $Category (optional) Name of the selected category, if it is empty ALL settings from ALL categories will be returned.
- * @return array Array of available settings
- * @access public
- * @final
- * @static
- */
- final public static function GetAllEntries($Category = null)
- {
- $returnArr = array();
- $data =& self::GetData();
- if(empty($Category))
- {
- $categories = self::GetAllCategories();
- foreach(array_keys($categories) as $categ)
- {
- if(isset($data[$categ]))
- $returnArr[$categ] = $data[$categ];
- else
- $returnArr[$categ] = array();
- }
- }
- else
- {
- if(isset($data[$Category]))
- $returnArr = $data[$Category];
- }
- return $returnArr;
- }
- /**
- * AddIncludePath()
- *
- * Add a path to the config include path
- *
- * @param string $Path A full qualified path for inclusion
- * @return void
- * @access public
- * @static
- * @final
- */
- final public static function AddIncludePath($Path)
- {
- $Path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, trim($Path));
- if(!empty($Path) && !in_array($Path, self::$include_path))
- {
- self::$include_path[] = $Path;
- }
- }
- /**
- * GetIncludePath()
- *
- * Get an array of all include paths
- * array('path1', 'path2')
- *
- * @return array Array of the include paths
- * @access public
- * @static
- * @final
- */
- final public static function GetIncludePath()
- {
- return self::$include_path;
- }
- /**
- * scanIncludePath()
- *
- * Scan all include path to find and inlcude necessary files.
- * Hidden files will be ignored for inclusion, also files with names containes ~, bak or -dist will be ignored.
- * Recursive directory searching will not be supported.
- *
- * @return void
- * @access public
- * @static
- * @final
- */
- final public static function ScanIncludePath()
- {
- $includePath = self::GetIncludePath();
- foreach($includePath as $i => $path)
- {
- if(is_dir($path))
- {
- $tmpDir = dir($path);
- while(($entry = $tmpDir->read()) !== false)
- {
- $fullFilename = $path .DIRECTORY_SEPARATOR .$entry;
- if(
- $entry == '.'
- || $entry == '..'
- || strpos($entry, '.') === 0 //hidden file or dirctory
- || is_dir($fullFilename)
- || substr($entry, -1) == '~' //unix "backup" files e.g. from VIM
- || substr($entry, -3) == 'bak' //.bak ... also backpfiles
- || strpos($entry, '-dist.') > 0
- )
- {
- continue; //ignore this file
- }
- else
- {
- self::ReadConfigFile($fullFilename);
- }
- }
- $tmpDir->close();
- }
- }
- }
- /**
- * RegisterConfigFileReader()
- *
- * Register a config reader for one file extension.
- * The registered reader have to be an instance of cfConfigFileReader class.
- * Beware: One extension for one reader. If you want to use one reader for more extensions you have to register it
- * separately for each extension.
- *
- * The reader class will be loaded via autoloader automaticly or you can include the class file befor loading the config.
- *
- * @param string $Extension File extension for the reader. e.g.: txt, ini, php, xml, ...
- * @return void
- * @access public
- * @static
- * @final
- */
- final public static function RegisterConfigFileReader($Extension, $Classname)
- {
- self::$configReaders[trim($Extension)] = trim($Classname);
- }
- /**
- * GetConfigFileReader()
- *
- * Get an instance of cfConfigFileReader for the defined file extension.
- * If not reader are defined the default reader will be registered. (Only for ini and php files).
- *
- * If not reader defined for the selected extension, so FALSE will be returned.
- *
- * @param string $Extension File extension for the reader. e.g.: txt, ini, php, xml, ...
- * @return cfConfigFileReader The instance of cfConfigFileReader for the designated file extension.
- * @access private
- * @static
- * @final
- */
- final private static function &GetConfigFileReader($Extension)
- {
- $ret = false;
- if(empty(self::$configReaders)) //set default values
- {
- self::RegisterConfigFileReader('php', 'cfConfigFileReader_PHP');
- self::RegisterConfigFileReader('ini', 'cfConfigFileReader_INI');
- }
- if(isset(self::$configReaders[$Extension]))
- {
- if(is_string(self::$configReaders[$Extension]))
- {
- $classname = self::$configReaders[$Extension];
- self::$configReaders[$Extension] = new $classname();
- }
- if(is_object(self::$configReaders[$Extension]) && self::$configReaders[$Extension] instanceof cfConfigFileReader)
- {
- $ret =& self::$configReaders[$Extension];
- }
- }
- return $ret;
- }
- /**
- * ReadConfigFile()
- *
- * Include one file and pars the settings.
- * Based on the filename, the category will be determined. Default = misc
- * File format: <category>[-_.]<qualifier>.<extension>
- *
- * @param string $FullFilename Filename to include and parse for settings
- * @return bool TRUE if the files was successfully readed
- * @access private
- * @static
- * @final
- */
- final private static function ReadConfigFile($FullFilename)
- {
- $FullFilename = trim($FullFilename);
- $path = dirname($FullFilename);
- $filename = basename($FullFilename);
- $options = array(
- 'filename' => '',
- 'category' => self::GetDefaultCategory(),
- 'qualifier' => '',
- 'extension' => ''
- );
- $matches = array();
- $result = preg_match('/^(?P<category>[^-_\.]+)(?:[-_\.]+(?P<qualifier>[^-_\.]+))?\.(?P<extension>[a-zA-Z]{3,4})/', $filename, $matches);
- if($result)
- {
- if(isset($matches['category']) && !empty($matches['category']))
- {
- $options['category'] = trim($matches['category']);
- }
- else $options['category'] = self::GetDefaultCategory();
- if(isset($matches['qualifier']) && !empty($matches['qualifier']))
- {
- $options['qualifier'] = trim($matches['qualifier']);
- }
- if(isset($matches['extension']) && !empty($matches['extension']))
- {
- $options['extension'] = trim($matches['extension']);
- }
- else
- {
- $options['extension'] = substr($filename, -3);
- }
- $options['filename'] = $filename;
- }
- if(($readerObj = self::GetConfigFileReader($options['extension'])) !== false)
- {
- $readerObj->SetFile($FullFilename);
- $settings = $readerObj->ReadFile();
- if(!empty($settings))
- {
- foreach($settings as $entry => $value)
- {
- self::SetEntry($entry, $value, $options['category']);
- }
- }
- }
- else
- {
- throw new cfException(__METHOD__ .': Could not get instance of cfConfigFileReader for ".' .$options['extension'] .'"');
- }
- }
- /**
- * dump()
- *
- * Dumps the complete config array direclty on screen.
- *
- * @return void
- * @access public
- */
- public function dump()
- {
- if(php_sapi_name() == 'cli')
- { //for command line output
- echo "\n" .print_r(self::$data, true) ."\n";
- }
- else
- { //for html output
- echo '<pre>' .print_r(self::$data, true) .'</pre>';
- }
- }
- }
- ?>