diff --git a/config.php b/config.php new file mode 100644 index 0000000..b26be3b --- /dev/null +++ b/config.php @@ -0,0 +1,109 @@ +default = array ("param"=>"default", + "param2"=>array (1,2,3), + "param3"=>null); +$var = $config->get ("param"); + */ +class config +{ + public $default = array (); // All the parameters allowed with their default + // value + public $confFile = "./datas/configuration.php"; // Use the .php to protect + // the informations by adding a killing feature in + // the file + + /** Get the value of the provided parameter recorded in .ini file + If it is not set in .ini file, use the default value */ + public function get ($param) + { + if (!array_key_exists ($param, $this->default)) + throw new Exception ("Unknown parameter '$param'"); + if (!file_exists ($this->confFile)) + { + if (@file_put_contents ($this->confFile, + "confFile)); + } + $conf = array (); + $rc = include ($this->confFile); + if ($rc !== 1) + throw new Exception ("Error in configuration file"); + if (array_key_exists ($param, $conf)) + return $conf[$param]; + return $this->default[$param]; + } + + /** Define a value for the parameter in the config file. Add all the default + values if they are not defined */ + public function set ($param, $value) + { + if (!array_key_exists ($param, $this->default)) + throw new Exception ("Unknown parameter '$param'"); + if (!file_exists ($this->confFile)) + { + if (@file_put_contents ($this->confFile, + "confFile)); + } + if (!is_writeable ($this->confFile)) + throw new Exception (sprintf ( + "Configuration file '%s' is write protected", + $this->confFile)); + $conf = array (); + $rc = include ($this->confFile); + if ($rc !== 1) + throw new Exception ("Error in configuration file"); + $newconf = array_merge ($this->default, $conf, array ($param=>$value)); + $txt = "writePHP ($newconf, $txt, 4); + $txt .= ");\r\n"; + + if (@file_put_contents ($this->confFile, $txt, LOCK_EX) === FALSE) + throw new Exception (sprintf ("Can't save configuration file '%s'", + $this->confFile)); + } + + private function writePHP ($values, $phpcode, $indent) + { + foreach ($values as $key=>$val) + { + $phpcode .= str_pad (" ", $indent); + $phpcode .= (is_numeric ($key)) ? $key : "\"$key\""; + $phpcode .= " => "; + if (is_bool ($val)) + { + if ($val === FALSE) $phpcode .= "FALSE,\r\n"; + else $phpcode .= "TRUE,\r\n"; + } + elseif (is_null ($val)) + $phpcode .= "NULL,\r\n"; + elseif (is_int ($val) || is_float ($val)) + $phpcode .= "$val,\r\n"; + elseif (is_string ($val)) + $phpcode .= "\"$val\",\r\n"; + elseif (is_array ($val)) + { + $phpcode .= "array (\r\n"; + $phpcode = $this->writePHP ($val, $phpcode, $indent+4); + $phpcode .= str_pad (" ", $indent); + $phpcode .= "),\r\n"; + } + else + throw new Exception ("Config : missing type ".gettype ($val)); + } + + return $phpcode; + } +}