openrat-cms

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

ConfigurationLoader.class.php (4266B)


      1 <?php
      2 
      3 namespace configuration;
      4 
      5 use util\text\variables\VariableResolver;
      6 use util\YAML;
      7 
      8 
      9 /**
     10  * Configuration Loader.
     11  *
     12  * Loades the configuration values from a YAML file.
     13  *
     14  * @author Jan Dankert
     15  * @package openrat.util
     16  */
     17 class ConfigurationLoader
     18 {
     19 	public $configFile;
     20 
     21 
     22 	/*
     23 	 * Erzeugt eine neue Instanz.
     24 	 */
     25 	public function __construct($configFile)
     26 	{
     27 		$this->configFile = $configFile;
     28 	}
     29 
     30 
     31 	/**
     32 	 * Ermittelt den Zeitpunkt der letzten Ă„nderung der Konfigurationsdatei.
     33 	 *
     34 	 * @return int Zeitpunkt der letzten Ă„nderung als Unix-Timestamp
     35 	 */
     36 	public function lastModificationTime()
     37 	{
     38 		return filemtime($this->configFile);
     39 	}
     40 
     41 
     42 	/**
     43 	 * Loads the custom configuration file.
     44 	 *
     45 	 * @return array Configuration
     46 	 */
     47 	public function load()
     48 	{
     49 		$customConfig = ConfigurationLoader::loadCustomConfig($this->configFile);
     50 
     51 		// Den Dateinamen der Konfigurationsdatei in die Konfiguration schreiben.
     52 		$customConfig['config']['filename'] = $this->configFile;
     53 		$customConfig['config']['last_modification_time'] = filemtime($this->configFile);
     54 		$customConfig['config']['last_modification'] = date('r', filemtime($this->configFile));
     55 		$customConfig['config']['read'] = date('r');
     56 
     57 		return $customConfig;
     58 	}
     59 
     60 
     61 	/**
     62 	 * Loads the configuration file and resolves all include-commands.
     63 	 *
     64 	 * @return array Configuration
     65 	 */
     66 	private function loadCustomConfig($configFile)
     67 	{
     68 		if (!is_file($configFile) && !is_link($configFile)) {
     69 			error_log('Warning: Configuration file ' . $configFile . ' not found');
     70 			return array();
     71 		}
     72 
     73 		$customConfig = YAML::parse(file_get_contents($configFile));
     74 
     75 		// resolve variables
     76 		$customConfig = self::resolveVariables($customConfig);
     77 
     78 		// enrich with environment variables
     79 		$customConfig = self::enrichEnvironmentVariables($customConfig, getenv('CMS_CONFIG_PREFIX')?:'CMS');
     80 
     81 		// Does we have includes?
     82 		if (isset($customConfig['include'])) {
     83 
     84 			// 'include' must be an array
     85 			if (is_string($customConfig['include']))
     86 				$customConfig['include'] = array($customConfig['include']);
     87 
     88 			// Load include files.
     89 			foreach ($customConfig['include'] as $key => $file) {
     90 
     91 				if ($file[0] == '/') // File begins with '?'
     92 					; // File has an absolute path - do not change.
     93 				else
     94 					// Prepend file path with our config directory.
     95 					$file = __DIR__ . '/../../config/' . $file;
     96 
     97 				if (substr($file, -4) == '.yml' ||
     98 					substr($file, -5) == '.yaml' ||
     99 					substr($file, -8) == '.yml.php')
    100 					$customConfig = array_replace_recursive($customConfig, self::loadCustomConfig($file));
    101 				else
    102 					error_log('Warning: ' . $file . ' is no .yml file - not loaded');
    103 
    104 			}
    105 		}
    106 
    107 		return $customConfig;
    108 	}
    109 
    110 	/**
    111 	 * Evaluates variables in a config array.
    112 	 * Examples:
    113 	 * - config-${http:host}.yml        => config-yourdomain.yml
    114 	 * - config-${server:http-host}.yml => config-yourdomain.yml
    115 	 * - config-${env:myvar}.yml        => config-myvalue.yml
    116 	 * @param $config array Configuration
    117 	 * @return array
    118 	 */
    119 	private function resolveVariables($config)
    120 	{
    121 		$resolver = new VariableResolver();
    122 		$resolver->namespaceSeparator = ':';
    123 		$resolver->defaultSeparator   = '?';
    124 
    125 		$resolver->addResolver('env',function ($var) {
    126 				return getenv(strtoupper($var));
    127 		});
    128 
    129 		// http:... is a shortcut for server:http-...
    130 		$resolver->addResolver('http', function ($var) {
    131 				return @$_SERVER['HTTP_' . strtoupper($var)];
    132 		});
    133 
    134 		$resolver->addResolver('server',function ($var) {
    135 				return @$_SERVER[strtoupper($var)];
    136 		});
    137 
    138 		return $resolver->resolveVariablesInArray($config);
    139 	}
    140 
    141 	/**
    142 	 * Test for environment variables.
    143 	 * @param $prefix string|array prefix
    144 	 * @return array
    145 	 */
    146 	private function enrichEnvironmentVariables($config, $prefix)
    147 	{
    148 		foreach ( $config as $key=>$value ) {
    149 			$newKey = array_merge( (array)$prefix,[$key] );
    150 			if   ( is_array($value) ) {
    151 				$value = $this->enrichEnvironmentVariables($value,$newKey );
    152 			} else {
    153 				$envKey = strtoupper( implode('_',$newKey ) );
    154 				//error_log( "get env ".$envKey );
    155 				$value = getenv( $envKey ) ?: $value;
    156 				if   ( in_array(strtolower($value),['true ','on' ]) )
    157 					$value = true;
    158 				if   ( in_array(strtolower($value),['false','off']) )
    159 					$value = false;
    160 			}
    161 			$config[$key] = $value;
    162 		}
    163 		return $config;
    164 	}
    165 
    166 }
    167