<?php
/**
 * Manages Blended User and theme settings configuration.
 *
 * Phpini Parser.
 *
 * @blended
 */

namespace Blended\hostlib;

class Blended_ini_Parser
{
    
    var $_iniFilename = '';
    var $_iniParsedArray = array();
    
    /** 
     *  it returns is a multidimensional array with section names and settings included. Default is FALSE
     **/
    function __construct($filename)
    {
        $this->_iniFilename = $filename;
        if ($this->_iniParsedArray = parse_ini_file($filename, true, INI_SCANNER_RAW)) {
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * get section name of multidimensional array.
     **/
    function getSection($key)
    {
        return $this->_iniParsedArray[$key];
    }
    
    /**
     *  get value of a section.
     **/
    function getValue($section, $key)
    {
        if (!isset($this->_iniParsedArray[$section]))
            return false;
        return $this->_iniParsedArray[$section][$key];
    }
    
    /**
     *  get specific section only.
     **/
    function get($section, $key = NULL)
    {
        if (is_null($key))
            return $this->getSection($section);
        return $this->getValue($section, $key);
    }
    
    /**
     * change section name here.
     **/
    function setSection($section, $array)
    {
        if (!is_array($array))
            return false;
        return $this->_iniParsedArray[$section] = $array;
    }
    
    /**
     * set value in defined section.
     **/
    function setValue($section, $key, $value)
    {
        if ($this->_iniParsedArray[$section][$key] = $value)
            return true;
    }
    
    /**
     * set empty section name.
     **/
    function set($section, $key, $value = NULL)
    {
        if (is_array($key) && is_null($value))
            return $this->setSection($section, $key);
        return $this->setValue($section, $key, $value);
    }
    
    /**
     * save Blended setting object.
     **/
    function save($filename = null)
    {
        if ($filename == null)
            $filename = $this->_iniFilename;
        if (is_writeable($filename)) {
            $SFfdescriptor = fopen($filename, "w");
            foreach ($this->_iniParsedArray as $section => $array) {
                fwrite($SFfdescriptor, "[" . $section . "]\n");
                foreach ($array as $key => $value) {
                    fwrite($SFfdescriptor, "$key = $value\n");
                }
                fwrite($SFfdescriptor, "\n");
            }
            fclose($SFfdescriptor);
            return true;
        } else {
            return false;
        }
    }
}

