/** * merges config files of each module imported via config.ini[modules] to one file and loads it * considering current environment [dev, production, ...] - separate config file for each * uses Nette/Cache for invalidation when one (or more) of config files changed * * @param string|null filepath * @return Config */ public static function load($baseConfigFile = null) { if ($baseConfigFile === null) { $baseConfigFile = Environment::expand(Environment::getConfigurator()->defaultConfigFile); } $envName = Environment::getName(); Environment::setVariable('tempDir', VAR_DIR . '/cache'); $cache = Environment::getCache('config'); $key = "config[{$envName}]"; if (!isset($cache[$key])) { // najviac casu zabera load, tak az tu, ked ho je treba $appConfig = Environment::loadConfig($baseConfigFile); $configs = array(Config::fromFile($baseConfigFile, $envName)->toArray()); $configPaths = array($baseConfigFile); foreach ($appConfig->modules as $c) { $configPaths[] = $path = MODULES_DIR . "/{$c}Module/config.ini"; if (file_exists($path)) { $configs[] = Config::fromFile($path, $envName)->toArray(); } } $arrayConfig = call_user_func_array('array_merge_recursive', $configs); $cache->save($key, $arrayConfig, array('files' => $configPaths)); } return Environment::loadConfig(new Config($cache[$key])); }
public function testSetRequestValidData() { $file = __DIR__ . "/../../resources/confitests.php"; $config = Config::fromFile($file, 'TEST'); $payment = new Payment($config); $request = new Container(); $requestData = array('PROVIDER' => 'ProviderTest', 'METHOD' => 'BILLET', 'clientID' => 1, 'value' => 14.9, 'product' => 'livro'); $request->fromArray($requestData); $payment->request($request); $this->assertInstanceOf('\\Ecomz\\Payment\\Payment', $payment); }
/** * @param Config $config * @param array $parameters * @throws \Exception */ public function __construct($config = NULL, $parameters = NULL) { if (!isset($config)) { $config = Config::fromFile(); if (!isset($config)) { throw new \Exception("No config file or object found for snoauth.", 500); } } $this->config = $config; if (!isset($parameters)) { $parameters = $_GET; // TODO: or whatever } $this->parameters = $parameters; }
Debug::$maxDepth = NULL; echo "Load INI\n"; $config = Config::fromFile('config1.ini'); Debug::dump($config); echo "toArray()\n"; Debug::dump($config->toArray()); echo "Save INI\n"; $config->save('tmp/cfg.ini'); readfile('tmp/cfg.ini'); echo "\n"; echo "Save section to INI\n"; $config->save('tmp/cfg.ini', 'mysection'); readfile('tmp/cfg.ini'); echo "\n"; echo "Load section from INI\n"; $config = Config::fromFile('config1.ini', 'development', NULL); Debug::dump($config); echo "Save INI\n"; $config->display_errors = true; $config->html_errors = false; $config->save('tmp/cfg.ini', 'mysection'); readfile('tmp/cfg.ini'); echo "\n"; try { echo "check read-only:\n"; $config->freeze(); $config->database->adapter = 'new value'; } catch (Exception $e) { echo get_class($e), ': ', $e->getMessage(), "\n\n"; } echo "check read-only clone:\n";
/** * Loads global configuration from file and process it. * @param string|Nette\Config\Config file name or Config object * @param bool * @return Nette\Config\Config */ public function loadConfig($file, $useCache) { if ($useCache === NULL) { $useCache = Environment::isLive(); } $cache = $useCache && $this->cacheKey ? Environment::getCache('Nette.Environment') : NULL; $name = Environment::getName(); $cacheKey = Environment::expand($this->cacheKey); if (isset($cache[$cacheKey])) { Environment::swapState($cache[$cacheKey]); $config = Environment::getConfig(); } else { if ($file instanceof Config) { $config = $file; $file = NULL; } else { if ($file === NULL) { $file = $this->defaultConfigFile; } $file = Environment::expand($file); $config = Config::fromFile($file, $name, 0); } // process environment variables if ($config->variable instanceof Config) { foreach ($config->variable as $key => $value) { Environment::setVariable($key, $value); } } if (PATH_SEPARATOR !== ';' && isset($config->set->include_path)) { $config->set->include_path = str_replace(';', PATH_SEPARATOR, $config->set->include_path); } $config->expand(); $config->setReadOnly(); // process services $locator = Environment::getServiceLocator(); if ($config->service instanceof Config) { foreach ($config->service as $key => $value) { $locator->addService($value, strtr($key, '-', '\\')); } } // save cache if ($cache) { $state = Environment::swapState(NULL); $state[0] = $config; // TODO: better! $cache->save($cacheKey, $state, array(Cache::FILES => $file)); } } // check temporary directory - TODO: discuss /* $dir = Environment::getVariable('tempDir'); if ($dir && !(is_dir($dir) && is_writable($dir))) { trigger_error("Temporary directory '$dir' is not writable", E_USER_NOTICE); } */ // process ini settings if ($config->set instanceof Config) { foreach ($config->set as $key => $value) { $key = strtr($key, '-', '.'); if (function_exists('ini_set')) { ini_set($key, $value); } else { switch ($key) { case 'include_path': set_include_path($value); break; case 'iconv.internal_encoding': iconv_set_encoding('internal_encoding', $value); break; case 'mbstring.internal_encoding': mb_internal_encoding($value); break; case 'date.timezone': date_default_timezone_set($value); break; case 'error_reporting': error_reporting($value); break; case 'ignore_user_abort': ignore_user_abort($value); break; case 'max_execution_time': set_time_limit($value); break; default: throw new NotSupportedException('Required function ini_set() is disabled.'); } } } } // define constants if ($config->const instanceof Config) { foreach ($config->const as $key => $value) { define($key, $value); } } // set modes if (isset($config->mode)) { foreach ($config->mode as $mode => $state) { Environment::setMode($mode, $state); } } return $config; }
/** * Loads global configuration from file and process it. * @param string|Config file name or Config object * @return Config */ public function loadConfig($file) { $name = Environment::getName(); if ($file instanceof Config) { $config = $file; $file = NULL; } else { if ($file === NULL) { $file = $this->defaultConfigFile; } $file = Environment::expand($file); $config = Config::fromFile($file, $name, 0); } // process environment variables if ($config->variable instanceof Config) { foreach ($config->variable as $key => $value) { Environment::setVariable($key, $value); } } $config->expand(); // process services $runServices = array(); $locator = Environment::getServiceLocator(); if ($config->service instanceof Config) { foreach ($config->service as $key => $value) { $key = strtr($key, '-', '\\'); // limited INI chars if (is_string($value)) { $locator->removeService($key); $locator->addService($key, $value); } else { if ($value->factory) { $locator->removeService($key); $locator->addService($key, $value->factory, isset($value->singleton) ? $value->singleton : TRUE, (array) $value->option); } if ($value->run) { $runServices[] = $key; } } } } // process ini settings if (!$config->php) { // backcompatibility $config->php = $config->set; unset($config->set); } if ($config->php instanceof Config) { if (PATH_SEPARATOR !== ';' && isset($config->php->include_path)) { $config->php->include_path = str_replace(';', PATH_SEPARATOR, $config->php->include_path); } foreach ($config->php as $key => $value) { // flatten INI dots if ($value instanceof Config) { unset($config->php->{$key}); foreach ($value as $k => $v) { $config->php->{"{$key}.{$k}"} = $v; } } } foreach ($config->php as $key => $value) { $key = strtr($key, '-', '.'); // backcompatibility if (!is_scalar($value)) { throw new InvalidStateException("Configuration value for directive '{$key}' is not scalar."); } if ($key === 'date.timezone') { // PHP bug #47466 date_default_timezone_set($value); } if (function_exists('ini_set')) { ini_set($key, $value); } else { switch ($key) { case 'include_path': set_include_path($value); break; case 'iconv.internal_encoding': iconv_set_encoding('internal_encoding', $value); break; case 'mbstring.internal_encoding': mb_internal_encoding($value); break; case 'date.timezone': date_default_timezone_set($value); break; case 'error_reporting': error_reporting($value); break; case 'ignore_user_abort': ignore_user_abort($value); break; case 'max_execution_time': set_time_limit($value); break; default: if (ini_get($key) != $value) { // intentionally == throw new NotSupportedException('Required function ini_set() is disabled.'); } } } } } // define constants if ($config->const instanceof Config) { foreach ($config->const as $key => $value) { define($key, $value); } } // set modes if (isset($config->mode)) { foreach ($config->mode as $mode => $state) { Environment::setMode($mode, $state); } } // auto-start services foreach ($runServices as $name) { $locator->getService($name); } $config->freeze(); return $config; }
<h1>Nette\Config\Config & ConfigAdapterIni test #3</h1> <pre> <?php require_once '../../Nette/loader.php'; /*use Nette\Config\Config;*/ /*use Nette\Debug;*/ try { echo "Example 3\n"; $config = Config::fromFile('config3.ini'); Debug::dump($config); } catch (Exception $e) { echo get_class($e), ': ', $e->getMessage(), "\n\n"; } try { echo "Example 4\n"; $config = Config::fromFile('config4.ini'); Debug::dump($config); } catch (Exception $e) { echo get_class($e), ': ', $e->getMessage(), "\n\n"; } try { echo "Example 5\n"; $config = Config::fromFile('config5.ini'); Debug::dump($config); } catch (Exception $e) { echo get_class($e), ': ', $e->getMessage(), "\n\n"; }
/** * @param Config $config defaults to Config::fromFile('frest-config.php') * @param string $resourceName The name of the resource for the request (defaults to base name of request url) * @param int|string $resourceID The ID of the resource for the request (defaults to base name of request url if it is an int) * @param array $parameters A list of key-value parameters to pass for the request (defaults to $_GET or $_POST) * @param int $requestMethod The method (get, post, put, delete) (e.g. FREST\Type\Method) of the request (defaults to REQUEST_METHOD) * @param string $resourceFunctionName Custom Func to be invoked on resource */ public function __construct($config = NULL, $resourceName = NULL, $resourceID = NULL, $parameters = NULL, $requestMethod = NULL, $resourceFunctionName = NULL) { try { $this->startTimingForLabel(Type\Timing::TOTAL, 'frest'); if (!isset($config)) { $config = Config::fromFile(); if (!isset($config)) { throw new Exception(Exception::Config, "No config file or object supplied to Router"); } } $this->config = $config; $this->suppressHTTPStatusCodes = $this->config->getSuppressHTTPStatusCodes(); $this->startTimingForLabel(Type\Timing::SETUP, 'frest'); // determine resource name, id, and Func (if any, taking into account if any of those were passed as parameters) if (!isset($resourceName) || !isset($resourceID)) { $url = $_SERVER['REQUEST_URI']; $queryPosition = strpos($url, '?'); if ($queryPosition !== FALSE) { $url = substr($url, 0, $queryPosition); } $urlInfo = pathinfo($url); $urlBaseName = $urlInfo['filename']; if (!isset($resourceName)) { // check if base name is int $secondBaseName = basename($urlInfo['dirname']); if (is_numeric($urlBaseName) && strpos($urlBaseName, '.') == NULL) { // assume this int is actually an id and resource is specified in previous path component $resourceName = basename($urlInfo['dirname']); $resourceID = intval($urlBaseName); } else { if (is_numeric($secondBaseName) && strpos($secondBaseName, '.') == NULL) { // assume this int is actually an id and resource precedes it and Func follows it $resourceName = basename(dirname($urlInfo['dirname'])); $resourceID = intval($secondBaseName); $resourceFunctionName = $urlBaseName; } else { $resourceName = $urlBaseName; } } } else { if (!isset($resourceID)) { $resourceNameIfNoFunctionUsed = basename($urlInfo['dirname']); $resourceNameIfFunctionUsed = basename(dirname($urlInfo['dirname'])); if ($resourceNameIfNoFunctionUsed == $resourceName) { $resourceID = $urlBaseName; } else { if ($resourceNameIfFunctionUsed == $resourceName) { $resourceID = basename($urlInfo['dirname']); $resourceFunctionName = $urlBaseName; } } } } } // cast resource ID if exists if (isset($resourceID)) { $resourceIDType = $this->resourceIDTypeFromResource($resourceName); $resourceID = Type\Variable::castValue($resourceID, $resourceIDType); } // determine request method if (!isset($requestMethod)) { $actualMethodString = $_SERVER['REQUEST_METHOD']; $actualMethod = Type\Method::fromString($actualMethodString); } else { $actualMethod = $requestMethod; } // check for forced method switch ($actualMethod) { case Type\Method::GET: case Type\Method::POST: if ($this->config->getEnableForcedMethod() && isset($_REQUEST['method'])) { $forcedMethodString = $_REQUEST['method']; $forcedMethod = Type\Method::fromString($forcedMethodString); // if method is valid if ($forcedMethod <= 0) { throw new Exception(Exception::InvalidMethod, "Method '{$forcedMethodString}"); } } break; } if (isset($forcedMethod)) { $this->method = $forcedMethod; } else { $this->method = $actualMethod; } // determine parameters to be used for resource if (!isset($parameters)) { switch ($actualMethod) { case Type\Method::GET: $parameters = $_GET; break; case Type\Method::POST: case Type\Method::PUT: case Type\Method::DELETE: $parameters = $this->config->getEnableGETParametersInAllRequests() ? $_REQUEST : $_POST; break; default: $methodString = Type\Method::getString($actualMethod); throw new Exception(Exception::InvalidMethod, "Method '{$methodString}"); break; } } if (isset($parameters['suppress_http_status_codes'])) { $value = $parameters['suppress_http_status_codes']; $this->suppressHTTPStatusCodes = Type\Variable::castValue($value, Type\Variable::BOOL); } switch ($this->method) { case Type\Method::GET: // read if (isset($resourceID) && $resourceID != self::FORCED_NULL) { $this->request = new Request\SingularRead($this, $resourceID, $parameters, $resourceFunctionName); } else { $this->request = new Request\PluralRead($this, $parameters, $resourceFunctionName); } break; case Type\Method::POST: // create $this->request = new Request\Create($this, $resourceID, $parameters, $resourceFunctionName); break; case Type\Method::PUT: // update / create $this->request = new Request\Update($this, $resourceID, $parameters, $resourceFunctionName); break; case Type\Method::DELETE: // delete $this->request = new Request\Delete($this, $resourceID, $parameters, $resourceFunctionName); break; default: break; } $this->resource = $this->loadResourceWithName($resourceName, $this->request); $this->stopTimingForLabel(Type\Timing::SETUP, 'frest'); $this->startTimingForLabel(Type\Timing::PROCESSING, 'frest'); $this->request->setupWithResource($this->resource); $this->stopTimingForLabel(Type\Timing::PROCESSING, 'frest'); $this->stopTimingForLabel(Type\Timing::TOTAL, 'frest'); } catch (Exception $exception) { $this->error = $exception->generateError(); } }
function loadConfig($file) { $name = Environment::getName(); if ($file instanceof Config) { $config = $file; $file = NULL; } else { if ($file === NULL) { $file = $this->defaultConfigFile; } $file = Environment::expand($file); $config = Config::fromFile($file, $name); } if ($config->variable instanceof Config) { foreach ($config->variable as $key => $value) { Environment::setVariable($key, $value); } } $iterator = new RecursiveIteratorIterator($config); foreach ($iterator as $key => $value) { $tmp = $iterator->getDepth() ? $iterator->getSubIterator($iterator->getDepth() - 1)->current() : $config; $tmp[$key] = Environment::expand($value); } $runServices = array(); $locator = Environment::getServiceLocator(); if ($config->service instanceof Config) { foreach ($config->service as $key => $value) { $key = strtr($key, '-', '\\'); if (is_string($value)) { $locator->removeService($key); $locator->addService($key, $value); } else { if ($value->factory) { $locator->removeService($key); $locator->addService($key, $value->factory, isset($value->singleton) ? $value->singleton : TRUE, (array) $value->option); } if ($value->run) { $runServices[] = $key; } } } } if (!$config->php) { $config->php = $config->set; unset($config->set); } if ($config->php instanceof Config) { if (PATH_SEPARATOR !== ';' && isset($config->php->include_path)) { $config->php->include_path = str_replace(';', PATH_SEPARATOR, $config->php->include_path); } foreach (clone $config->php as $key => $value) { if ($value instanceof Config) { unset($config->php->{$key}); foreach ($value as $k => $v) { $config->php->{"{$key}.{$k}"} = $v; } } } foreach ($config->php as $key => $value) { $key = strtr($key, '-', '.'); if (!is_scalar($value)) { throw new InvalidStateException("Configuration value for directive '{$key}' is not scalar."); } if ($key === 'date.timezone') { date_default_timezone_set($value); } if (function_exists('ini_set')) { ini_set($key, $value); } else { switch ($key) { case 'include_path': set_include_path($value); break; case 'iconv.internal_encoding': iconv_set_encoding('internal_encoding', $value); break; case 'mbstring.internal_encoding': mb_internal_encoding($value); break; case 'date.timezone': date_default_timezone_set($value); break; case 'error_reporting': error_reporting($value); break; case 'ignore_user_abort': ignore_user_abort($value); break; case 'max_execution_time': set_time_limit($value); break; default: if (ini_get($key) != $value) { throw new NotSupportedException('Required function ini_set() is disabled.'); } } } } } if ($config->const instanceof Config) { foreach ($config->const as $key => $value) { define($key, $value); } } if (isset($config->mode)) { foreach ($config->mode as $mode => $state) { Environment::setMode($mode, $state); } } foreach ($runServices as $name) { $locator->getService($name); } return $config; }
/** * Loads global configuration from file and process it. * @param string|Nette\Config\Config file name or Config object * @return Config */ public function loadConfig($file) { $name = Environment::getName(); if ($file instanceof Config) { $config = $file; $file = NULL; } else { if ($file === NULL) { $file = $this->defaultConfigFile; } $file = Environment::expand($file); $config = Config::fromFile($file, $name, 0); } // process environment variables if ($config->variable instanceof Config) { foreach ($config->variable as $key => $value) { Environment::setVariable($key, $value); } } $config->expand(); // process services $locator = Environment::getServiceLocator(); if ($config->service instanceof Config) { foreach ($config->service as $key => $value) { $locator->addService($value, strtr($key, '-', '\\')); } } // check temporary directory - TODO: discuss /* $dir = Environment::getVariable('tempDir'); if ($dir && !(is_dir($dir) && is_writable($dir))) { trigger_error("Temporary directory '$dir' is not writable", E_USER_NOTICE); } */ // process ini settings if ($config->set instanceof Config) { if (PATH_SEPARATOR !== ';' && isset($config->set->include_path)) { $config->set->include_path = str_replace(';', PATH_SEPARATOR, $config->set->include_path); } foreach ($config->set as $key => $value) { $key = strtr($key, '-', '.'); // old INI compatibility if (!is_scalar($value)) { throw new InvalidStateException("Configuration value for directive '{$key}' is not scalar."); } if (function_exists('ini_set')) { ini_set($key, $value); } else { switch ($key) { case 'include_path': set_include_path($value); break; case 'iconv.internal_encoding': iconv_set_encoding('internal_encoding', $value); break; case 'mbstring.internal_encoding': mb_internal_encoding($value); break; case 'date.timezone': date_default_timezone_set($value); break; case 'error_reporting': error_reporting($value); break; case 'ignore_user_abort': ignore_user_abort($value); break; case 'max_execution_time': set_time_limit($value); break; default: if (ini_get($key) != $value) { // intentionally == throw new NotSupportedException('Required function ini_set() is disabled.'); } } } } } // define constants if ($config->const instanceof Config) { foreach ($config->const as $key => $value) { define($key, $value); } } // set modes if (isset($config->mode)) { foreach ($config->mode as $mode => $state) { Environment::setMode($mode, $state); } } $config->setReadOnly(); return $config; }
/** * Parses the global configuration file and that of each * application. */ protected function parseconf() { // Loading the main configuration file first so we can get the paths. $this->conf = Config::fromArray(array('prefix' => '', 'apps_path' => 'apps', 'models_path' => 'models', 'helpers_path' => 'helpers', 'exceptions_path' => 'exceptions', 'modules_path' => 'lib/modules', 'apps' => array(), 'modules' => array())); // Defaults $this->conf->loadFile($this->conf_path); if ($this->conf->get('prefix')) { $this->server->setPrefix($this->prefix); } // Alright. Now let's load the apps config. We'll merge the apps routes as we go along. foreach ($this->conf->get('apps', array()) as $appname) { $path = Utils::joinPaths($this->conf->get('apps_path'), $appname, 'conf.php'); try { $this->apps_conf[$appname] = Config::fromFile($path, 'app'); } catch (\Exception $e) { continue; } // Little shortcut to help readability $app = $this->apps_conf[$appname]; $this->router->setRoutes($appname, $app->get('route')); // Let's merge in the modules, they'll be common to all apps. $modules = $this->conf->get('modules', array()); if ($app->get('modules')) { foreach ($app->get('modules') as $module) { if (!in_array($module, $modules)) { $modules[] = $module; if ($app->get($module)) { // Module-specific options. $this->conf->set($module, $app->get($module)); } } } } } $this->server->setMainConf($this->conf); }
/** * @expectedException \ErrorException */ public function testConfigFileNotExisting() { $config = Config::fromFile(__DIR__ . '/Config/foo_config.php'); }
/** * @expectedException Ecomz\Payment\Exception * @expectedExceptionMessage File Env:[OTHER2] Not Found */ public function testLoadFromFileNotValidEnvironment() { $file = __DIR__ . "/../../resources/confitests.php"; $config = Config::fromFile($file, 'OTHER2'); }