Introduced ConfigValueTypeUnsupportedException
[core.git] / inc / config / class_FrameworkConfiguration.php
index 85da3032725ef2bad673906d1d7e45aea99252a1..d6ff28a24da1226428e14824e42cf8e6ccfb462d 100644 (file)
@@ -6,11 +6,11 @@
  * class loader. See inc/loader/class_ClassLoader.php for instance
  *
  * @see                        ClassLoader
- * @author             Roland Haeder <webmaster@ship-simu.org>
+ * @author             Roland Haeder <webmaster@shipsimu.org>
  * @version            0.0.0
- * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 Core Developer Team
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Core Developer Team
  * @license            GNU GPL 3.0 or any newer version
- * @link               http://www.ship-simu.org
+ * @link               http://www.shipsimu.org
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -36,11 +36,12 @@ class FrameworkConfiguration implements Registerable {
        /**
         * The configuration instance itself
         */
-       private static $configInstance = null;
+       private static $configInstance = NULL;
 
        // Some constants for the configuration system
-       const EXCEPTION_CONFIG_ENTRY_IS_EMPTY      = 0x130;
-       const EXCEPTION_CONFIG_ENTRY_WAS_NOT_FOUND = 0x131;
+       const EXCEPTION_CONFIG_KEY_IS_EMPTY           = 0x130;
+       const EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND      = 0x131;
+       const EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED = 0x132;
 
        /**
         * Protected constructor
@@ -52,134 +53,244 @@ class FrameworkConfiguration implements Registerable {
        }
 
        /**
-        * Getter for an instance of this class
+        * Compatiblity method to return this class' name
         *
-        * @return      $configInstance An instance of this class
+        * @return      __CLASS__       This class' name
         */
-       public final static function getInstance () {
+       public function __toString () {
+               return get_class($this);
+       }
+
+       /**
+        * Getter for a singleton instance of this class
+        *
+        * @return      $configInstance         A singleton instance of this class
+        */
+       public static final function getSelfInstance () {
                // is the instance there?
                if (is_null(self::$configInstance))  {
                        // Create a config instance
                        self::$configInstance = new FrameworkConfiguration();
                } // END - if
 
+               // Return singleton instance
                return self::$configInstance;
        }
 
+       /**
+        * Converts dashes to underscores, e.g. useable for configuration entries
+        *
+        * @param       $str    The string with maybe dashes inside
+        * @return      $str    The converted string with no dashed, but underscores
+        */
+       private final function convertDashesToUnderscores ($str) {
+               // Convert them all
+               $str = str_replace('-', '_', $str);
+
+               // Return converted string
+               return $str;
+       }
+
        /**
         * Setter for default time zone (must be correct!)
         *
-        * @param               $zone   The time-zone string (e.g. Europe/Berlin)
+        * @param       $zone   The time-zone string (e.g. Europe/Berlin)
         * @return      void
         */
        public final function setDefaultTimezone ($zone) {
-               // At least 5.1.0 is required for this!
-               if (version_compare(phpversion(), "5.1.0")) {
-                       @date_default_timezone_set($zone);
+               // Is PHP version 5.1.0 or higher? Older versions are being ignored
+               if (version_compare(phpversion(), '5.1.0', '>=')) {
+                       /*
+                        * Set desired time zone to prevent date() and related functions to
+                        * issue a E_WARNING.
+                        */
+                       date_default_timezone_set($zone);
                } // END - if
        }
 
        /**
         * Setter for runtime magic quotes
+        *
+        * @param       $enableQuotes   Whether enable magic runtime quotes (should be disabled for security reasons)
+        * @return      void
+        * @todo        This method encapsulates a deprecated PHP function and should be deprecated, too.
         */
        public final function setMagicQuotesRuntime ($enableQuotes) {
+               // Is the PHP version < 5.4?
+               if (version_compare(phpversion(), '5.4', '>=')) {
+                       // Then silently skip this part as set_magic_quotes_runtime() is deprecated
+                       return;
+               } // END - if
+
                // Cast it to boolean
                $enableQuotes = (boolean) $enableQuotes;
 
                // Set it
-               @set_magic_quotes_runtime($enableQuotes);
+               set_magic_quotes_runtime($enableQuotes);
        }
 
        /**
-        * A private include loader
+        * Checks whether the given configuration key is set
         *
-        * @param       $arrayObject    The array object with all include files
-        * @return      void
+        * @param       $configKey      The configuration key we shall check
+        * @return      $isset          Whether the given configuration key is set
         */
-       private function loadIncludes (ArrayObject $arrayObject) {
-               // Load only if there are includes defined
-               if (!is_null($arrayObject)) {
-                       for ($idx = $arrayObject->getIterator(); $idx->valid(); $idx->next()) {
-                               // Get include file
-                               $inc = $idx->current();
-
-                               // Is the file name really set?
-                               if (!empty($inc)) {
-                                       // Base path is by default added
-                                       $fqfn = $inc;
-
-                                       // Base path added? (Uni* / Windows)
-                                       if ((substr($inc, 0, 1) != '/') && (substr($inc, 1, 1) != ':')) {
-                                               // Generate FQFN
-                                               $fqfn = $this->readConfig('base_path') . '/inc/extra/' . $inc;
-                                       } // END - if
-                               } // END - if
-
-                               // Include them all here
-                               require($fqfn);
-                       }
-               } // END - if
+       public function isConfigurationEntrySet ($configKey) {
+               // Is it set?
+               $isset = isset($this->config[$configKey]);
+
+               // Return the result
+               return $isset;
        }
 
        /**
         * Read a configuration element.
         *
-        * @param       $cfgEntry       The configuration element
-        * @return      $cfgValue       The fetched configuration value
-        * @throws      ConfigEntryIsEmptyException             If $cfgEntry is empty
-        * @throws      ConfigEntryNotFoundException    If a configuration element
-        *                                                                                      was not found
+        * @param       $configKey              The configuration element
+        * @return      $configValue    The fetched configuration value
+        * @throws      ConfigEntryIsEmptyException             If $configKey is empty
+        * @throws      NoConfigEntryException                  If a configuration element was not found
         */
-       public function readConfig ($cfgEntry) {
-               // Cast to string
-               $cfgEntry = (string) $cfgEntry;
+       public function getConfigEntry ($configKey) {
+               // Convert dashes to underscore
+               $configKey = $this->convertDashesToUnderscores($configKey);
 
-               // Is a valid configuration entry provided?
-               if (empty($cfgEntry)) {
+               // Is a valid configuration key provided?
+               if (empty($configKey)) {
                        // Entry is empty
-                       throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_ENTRY_IS_EMPTY);
-               } elseif (!isset($this->config[$cfgEntry])) {
+                       throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
+               } elseif (!$this->isConfigurationEntrySet($configKey)) {
                        // Entry was not found!
-                       throw new ConfigEntryNotFoundException(array(__CLASS__, $cfgEntry), self::EXCEPTION_CONFIG_ENTRY_WAS_NOT_FOUND);
+                       throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
                }
 
                // Return the requested value
-               return $this->config[$cfgEntry];
+               return $this->config[$configKey];
        }
 
        /**
-        * Set a configuration entry.
+        * Set a configuration key
         *
-        * @param       $cfgEntry       The configuration entry we want to add/change
-        * @param       $cfgValue       The configuration value we want to set
+        * @param       $configKey      The configuration key we want to add/change
+        * @param       $configValue    The configuration value we want to set
         * @return      void
-        * @throws      ConfigEntryIsEmptyException     If $cfgEntry is empty
+        * @throws      ConfigEntryIsEmptyException                     If $configKey is empty
+        * @throws      ConfigValueTypeUnsupportedException     If $configValue has an unsupported variable type
         */
-       public final function setConfigEntry ($cfgEntry, $cfgValue) {
+       public final function setConfigEntry ($configKey, $configValue) {
                // Cast to string
-               $cfgEntry = (string) $cfgEntry;
-               $cfgValue = (string) $cfgValue;
+               $configKey = $this->convertDashesToUnderscores($configKey);
 
-               // Is a valid configuration entry provided?
-               if (empty($cfgEntry)) {
+               // Is a valid configuration key key provided?
+               if ((empty($configKey)) || (!is_string($configKey))) {
                        // Entry is empty
-                       throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_ENTRY_IS_EMPTY);
-               } // END - if
+                       throw new ConfigEntryIsEmptyException($this, self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
+               } elseif ((is_null($configValue)) || (is_array($configValue)) || (is_object($configValue)) || (is_resource($configValue))) {
+                       // These cannot be set as this is not intended for configuration values, please use FrameworkArrayObject instead.
+                       throw new ConfigValueTypeUnsupportedException(array($this, $configKey, $configValue), self::EXCEPTION_CONFIG_VALUE_TYPE_UNSUPPORTED);
+               }
 
                // Set the configuration value
-               $this->config[$cfgEntry] = $cfgValue;
+               //* NOISY-DEBUG: */ print(__METHOD__ . ':configEntry=' . $configKey . ',configValue[' . gettype($configValue) . ']=' . $configValue . PHP_EOL);
+               $this->config[$configKey] = $configValue;
 
                // Resort the array
                ksort($this->config);
        }
 
        /**
-        * Compatiblity method to return this class' name
+        * Unset a configuration key, the entry must be there or else an
+        * exception is thrown.
         *
-        * @return      __CLASS__               This class' name
+        * @param       $configKey      Configuration key to unset
+        * @return      void
+        * @throws      NoConfigEntryException  If a configuration element was not found
         */
-       public function __toString () {
-               return get_class($this);
+       public final function unsetConfigEntry ($configKey) {
+               // Convert dashes to underscore
+               $configKey = $this->convertDashesToUnderscores($configKey);
+
+               // Is the configuration key there?
+               if (!$this->isConfigurationEntrySet($configKey)) {
+                       // Entry was not found!
+                       throw new NoConfigEntryException(array(__CLASS__, $configKey), self::EXCEPTION_CONFIG_KEY_WAS_NOT_FOUND);
+               } // END - if
+
+               // Unset it
+               unset($this->config[$configKey]);
+       }
+
+       /**
+        * Detects the server address (SERVER_ADDR) and set it in configuration
+        *
+        * @return      $serverAddress  The detected server address
+        * @todo        We have to add some more entries from $_SERVER here
+        */
+       public function detectServerAddress () {
+               // Is the entry set?
+               if (!$this->isConfigurationEntrySet('server_addr')) {
+                       // Is it set in $_SERVER?
+                       if (isset($_SERVER['SERVER_ADDR'])) {
+                               // Set it from $_SERVER
+                               $this->setServerAddress($_SERVER['SERVER_ADDR']);
+                       } elseif (class_exists('ConsoleTools')) {
+                               // Run auto-detecting through console tools lib
+                               ConsoleTools::acquireSelfIPAddress();
+                       }
+               } // END - if
+
+               // Now get it from configuration
+               $serverAddress = $this->getServerAddress();
+
+               // Return it
+               return $serverAddress;
+       }
+
+       /**
+        * Setter for SERVER_ADDR
+        *
+        * @param       $serverAddress  New SERVER_ADDR value to set
+        * @return      void
+        */
+       public function setServerAddress ($serverAddress) {
+               $this->setConfigEntry('server_addr', (string) $serverAddress);
+       }
+
+       /**
+        * Getter for SERVER_ADDR
+        *
+        * @return      $serverAddress  New SERVER_ADDR value to set
+        */
+       public function getServerAddress () {
+               return $this->getConfigEntry('server_addr');
+       }
+
+       /**
+        * Detects the HTTPS flag
+        *
+        * @return      $https  The detected HTTPS flag or null if failed
+        */
+       public function detectHttpSecured () {
+               // Default is null
+               $https = NULL;
+
+               // Is HTTPS set?
+               if ($this->isHttpSecured()) {
+                       // Then use it
+                       $https = $_SERVER['HTTPS'];
+               } // END - if
+
+               // Return it
+               return $https;
+       }
+
+       /**
+        * Checks whether HTTPS is set in $_SERVER
+        *
+        * @return $isset       Whether HTTPS is set
+        */
+       public function isHttpSecured () {
+               return (isset($_SERVER['HTTPS']));
        }
 
        /**
@@ -187,12 +298,12 @@ class FrameworkConfiguration implements Registerable {
         *
         * @return      $baseUrl        Detected base URL
         */
-       public function detectBaseUrl() {
+       public function detectBaseUrl () {
                // Initialize the URL
                $baseUrl = 'http';
 
                // Do we have HTTPS?
-               if (isset($_SERVER['HTTPS'])) {
+               if ($this->isHttpSecured()) {
                        // Add the >s< for HTTPS
                        $baseUrl .= 's';
                } // END - if
@@ -253,6 +364,45 @@ class FrameworkConfiguration implements Registerable {
        public final function getField ($fieldName) {
                // Our super interface "FrameworkInterface" requires this
        }
+
+       /**
+        * Checks if given field is set
+        *
+        * @param       $fieldName      Field name to check
+        * @return      $isSet          Whether the given field name is set
+        * @throws      NullPointerException    If the result instance is null
+        */
+       public function isFieldSet ($fieldName) {
+               // Our super interface "FrameworkInterface" requires this
+       }
+
+       /**
+        * Generates a code for hashes from this class
+        *
+        * @return      $hashCode       The hash code respresenting this class
+        */
+       public function hashCode () {
+               return crc32($this->__toString());
+       }
+
+       /**
+        * Checks whether an object equals this object. You should overwrite this
+        * method to implement own equality checks
+        *
+        * @param       $objectInstance         An instance of a FrameworkInterface object
+        * @return      $equals                         Whether both objects equals
+        */
+       public function equals (FrameworkInterface $objectInstance) {
+               // Now test it
+               $equals = ((
+                       $this->__toString() == $objectInstance->__toString()
+               ) && (
+                       $this->hashCode() == $objectInstance->hashCode()
+               ));
+
+               // Return the result
+               return $equals;
+       }
 }
 
 // [EOF]