Skip to content

Instantly share code, notes, and snippets.

@xergio
Created February 21, 2012 15:09
Show Gist options
  • Save xergio/1876964 to your computer and use it in GitHub Desktop.
Save xergio/1876964 to your computer and use it in GitHub Desktop.
ConfigParser.py semiclone in PHP
<?php
class ConfigParser {
private $_raw;
private $_ini;
private $_allow_no_value=false;
function __construct($allow_no_value=false) {
$this->_allow_no_value = $allow_no_value;
}
function read($inifile) {
$this->_raw = file_get_contents($inifile);
$this->_ini = $this->parse();
return $this->_ini;
}
function write($inifile) {
$content = $this->build();
return file_put_contents($inifile, $content);
}
private function parse() {
$lines = preg_split("#[\r?\n]+#", $this->_raw);
$section = "DEFAULT";
$ini = array();
foreach ($lines as $line) {
$line = trim($line);
if (preg_match("#^[;\#]#", $line)) continue;
if (preg_match("#^\[(.*)\]$#", $line, $m)) {
$section = $m[1];
$ini[$section] = array();
continue;
}
if (preg_match("#^(?P<key>[^=\s\t]+)[\t\s]*=[\t\s]*(?P<value>[^;\#\s\t]+)#", $line, $m)) {
$ini[$section][$m['key']] = $m['value'];
continue;
}
if ($this->_allow_no_value and preg_match("#^(?P<key>[^;\#\s\t]+)#", $line, $m)) {
$ini[$section][$m['key']] = null;
continue;
}
}
return $ini;
}
private function build($inifile) {
$content = "";
foreach ($this->_ini as $section_or_key => $set) {
if (!is_array($set))
$content .= $this->_build_var($section_or_key, $set);
else {
$content .= $this->_build_section($section_or_key);
foreach ($set as $k => $v)
$content .= $this->_build_var($k, $v);
}
}
return $content;
}
private function _build_var($k, $v) {
if ($this->_allow_no_value and $v === null) return $k."\n";
else return $k ." = ". $v."\n";
}
private function _build_section($s) {
return "\n[". $s ."]\n";
}
public function defaults() {
return $this->_ini["DEFAULT"];
}
public function sections() {
return array_diff(array_keys($this->_ini). array('DEFAULT'));
}
public function add_section($section) {
$this->_ini[$section] = array();
}
public function has_section($section) {
return array_key_exists($section, $this->_ini);
}
public function options($section) {
return $this->_ini[$section];
}
public function has_option($section, $option) {
return array_key_exists($option, $this->_ini[$section]);
}
public function set($section, $option, $value) {
$this->_ini[$section][$option] = $value;
}
public function remove_option($section, $option) {
unset($this->_ini[$section][$option]);
}
public function remove_section($section) {
unset($this->_ini[$section]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment