<?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) 2008 - 2014 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flRegistry Class
 *
 * Singleton class to hold and manage global data and objects.
 *
 * @package fusionLib
 */
class flRegistry {
	/**
	 * The store for objects and values added to the registry.
	 *
	 * @var array
	 */
	private $store = array();

	/**
	 * The instance of the registry.
	 *
	 * @var flRegistry
	 */
	static private $instance = null;

	/**
	 * Get the instance of the registry object.
	 *
	 * @return flRegistry
	 */
	static function getInstance() {
		return self::$instance !== null ? self::$instance : self::$instance = new flRegistry();
	}

	/**
	 * Set the registy object to use.
	 *
	 * Throws and error if the registry already initialised.
	 *
	 * @param flRegistry $obj The registry object to use.
	 * @throws flRegistryException
	 */
	static function setInstance($obj) {
		if(self::$instance === null)
			self::$instance = $obj;
		else
			throw new flRegistryException('Registry already initialized in setInstance.');
	}

	/**
	 * Store a value into the registry.
	 *
	 * @param string $name The name of the value to store.
	 * @param mixed $value The value to store.
	 */
	static function store($name, $value) {
		$instance = self::getInstance();
		$instance->store[$name] = $value;
	}

	/**
	 * Fetch a value from the registry, if it doesn't exist an exception is thrown.
	 *
	 * @param string $name The name of the value to get.
	 * @throws flRegistryException
	 * @return mixed The value fetched from the registry.
	 */
	static function fetch($name) {
		$instance = self::getInstance();
		if(!isset($instance->store[$name]))
			throw new flRegistryException("Unknown registry entry '$name'.");
		return $instance->store[$name];
	}

	/**
	 * Get a value from the registry, if it doesn't exist return the default value.
	 *
	 * @param string $name The name of the value to get.
	 * @param mixed $default The default value to return.
	 * @throws flRegistryException
	 * @return mixed The value fetched from the registry.
	 */
	static function get($name, $default = null) {
		$instance = self::getInstance();
		if(!isset($instance->store[$name]))
			return $default;
		return $instance->store[$name];
	}

	/**
	 * Remove a value from the registry.
	 *
	 * @param string $name The name of the value to remove.
	 */
	static function remove($name) {
		$instance = self::getInstance();
		unset($instance->store[$name]);
	}

	/**
	 * Tests if the named value exists in the registry.
	 *
	 * @param string $name The name of the item to test for.
	 * @return bool true if the item is present; else false.
	 */
	static function exists($name) {
		$instance = self::getInstance();
		return isset($instance->store[$name]);
	}
}
