<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2012 - 2013 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flConfigDb Class
 *
 * Class to provide access to configuration data held in the database.
 *
 * @package fusionLib
 */
class flConfigDb extends flConfig {

	/**
	 * The database object.
	 *
	 * @var flDb
	 */
	protected $db;

	/**
	 * The table to store the data in.
	 *
	 * @var string
	 */
	protected $table;

	/**
	 * Construct a new configuration object.
	 *
	 * Can load a PHP configuration file, the file must hold a single array called $config
	 * from which the configuration is loaded.
	 *
	 * @param string $namespace Name of the configuration data to load.
	 * @param flDb $db The database to use to read the data.
	 * @param string $table The name of the database table to use for storage.
	 */
	function __construct($namespace, $db, $table = 'fl_config') {
		$this->db = $db;
		$this->table = $table;
		$data = array();
		$result = $db->query("SELECT keyname,value FROM $this->table WHERE namespace=?", $namespace);
		while($row = $result->fetch())
			$data[$row['keyname']] = $row['value'];
		parent::__construct($namespace, $data);
	}

	/**
	 * Delete all the configuration items in the namespace.
	 */
	function deleteNamespace() {
		$this->db->delete($this->table, 'namespace=?', $this->namespace);
	}

	/**
	 * Set a configuration item.
	 *
	 * Configurations are read only therefore this throws an exception.
	 *
	 * @param string $key The name of the configuration item to set.
	 * @param mixed $value The value to set for the item.
	 */
	function __set($key, $value) {
		$this->db->replace($this->table, array('namespace' => $this->namespace, 'keyname' => $key, 'value' => $value));
		$this->data[$key] = $value;
	}

	/**
	 * Unset a configuration item.
	 *
	 * Configurations are read only therefore this throws an exception.
	 *
	 * @param string $key The name of the configuration item to unset.
	 */
	function __unset($key) {
		$this->db->delete($this->table, 'namespace=? && keyname=?', $this->namespace, $key);
		unset($this->data[$key]);
	}
}
