Read config options from a config file and setup the library

@param string        $sConfigFile        The full path to the config file

@return Jaxon
430487
public function setup($sConfigFile)
    {
        $aConfigOptions = $this->config()->read($sConfigFile);

        // Setup the config options into the library.
        $sLibKey = 'lib';
        $xLibConfig = $this->di()->getConfig();
        $xLibConfig->setOptions($aConfigOptions, $sLibKey);

        $sAppKey = 'app';
        $xAppConfig = new \Jaxon\Config\Config();
        $xAppConfig->setOptions($aConfigOptions, $sAppKey);

        // Register user functions and classes
        $this->getPluginManager()->registerFromConfig($xAppConfig);

        return $this;
    }
824436
public function init(\SplFileInfo $file, $extension = null)
    {
        $config = Grav::instance()['config'];

        // some extension logic
        if (empty($extension)) {
            $this->extension('.' . $file->getExtension());
        } else {
            $this->extension($extension);
        }

        // extract page language from page extension
        $language = trim(basename($this->extension(), 'md'), '.') ?: null;
        $this->language($language);

        $this->hide_home_route = $config->get('system.home.hide_in_urls', false);
        $this->home_route = $this->adjustRouteCase($config->get('system.home.alias'));
        $this->filePath($file->getPathname());
        $this->modified($file->getMTime());
        $this->id($this->modified() . md5($this->filePath()));
        $this->routable(true);
        $this->header();
        $this->date();
        $this->metadata();
        $this->url();
        $this->visible();
        $this->modularTwig(strpos($this->slug(), '_') === 0);
        $this->setPublishState();
        $this->published();
        $this->urlExtension();


        return $this;
    }
174921
public function actionTemplate($configFile)
    {
        $jsCompressor = VarDumper::export($this->jsCompressor);
        $cssCompressor = VarDumper::export($this->cssCompressor);

        $template = <<<EOD
<?php
/**
 * Configuration file for the "yii asset" console command.
 */

// In the console environment, some path aliases may not exist. Please define these:
// \$this->app->setAlias('@webroot', __DIR__ . '/../web');
// \$this->app->setAlias('@web', '/');

return [
    // Adjust command/callback for JavaScript files compressing:
    'jsCompressor' => {$jsCompressor},
    // Adjust command/callback for CSS files compressing:
    'cssCompressor' => {$cssCompressor},
    // Whether to delete asset source after compression:
    'deleteSource' => false,
    // The list of asset bundles to compress:
    'bundles' => [
        // 'app\assets\AppAsset',
        // \yii\web\YiiAsset::class,
        // \yii\web\JqueryAsset::class,
    ],
    // Asset bundle for compression output:
    'targets' => [
        'all' => [
            '__class' => \yii\web\AssetBundle::class,
            'basePath' => '@webroot/assets',
            'baseUrl' => '@web/assets',
            'js' => 'js/all-{hash}.js',
            'css' => 'css/all-{hash}.css',
        ],
    ],
    // Asset manager configuration:
    'assetManager' => [
        //'basePath' => '@webroot/assets',
        //'baseUrl' => '@web/assets',
    ],
];
EOD;
        if (file_exists($configFile)) {
            if (!$this->confirm("File '{$configFile}' already exists. Do you wish to overwrite it?")) {
                return ExitCode::OK;
            }
        }
        if (!file_put_contents($configFile, $template, LOCK_EX)) {
            throw new Exception("Unable to write template file '{$configFile}'.");
        }

        $this->stdout("Configuration file template created at '{$configFile}'.\n\n", Console::FG_GREEN);
        return ExitCode::OK;
    }
776092
public CmsUgcConfiguration readConfiguration(CmsFile configFile) throws CmsException {

        m_content = CmsXmlContentFactory.unmarshal(m_cms, configFile);
        String resourceType = getStringValue(N_CONTENT_TYPE);
        String contentPath = getStringValue(N_CONTENT_PATH);
        CmsResource contentPathResource = m_cms.readResource(contentPath);
        String namePattern = getStringValue(N_NAME_PATTERN);
        String localeStr = getStringValue(N_LOCALE);
        OpenCms.getLocaleManager();
        Locale locale = CmsLocaleManager.getLocale(localeStr);
        Optional<CmsResource> uploadPathResource = Optional.absent();
        String uploadPath = getStringValue(N_UPLOAD_PATH);
        if (uploadPath != null) {
            uploadPathResource = Optional.of(m_cms.readResource(uploadPath));
        }
        Optional<Long> maxUploadSize = getLongValue(N_MAX_UPLOAD_SIZE);
        Optional<Integer> maxNumContents = getIntValue(N_MAX_NUM_CONTENTS);
        Optional<Long> queueWaitTime = getLongValue(N_QUEUE_WAIT_TIME);
        Optional<Integer> maxQueueLength = getIntValue(N_QUEUE_MAX_LENGTH);
        boolean autoPublish = Boolean.parseBoolean(getStringValue(N_AUTO_PUBLISH));
        String validExtensionsStr = getStringValue(N_VALID_EXTENSIONS);
        Optional<List<String>> validExtensions = Optional.absent();
        if (validExtensionsStr != null) {
            validExtensionsStr = validExtensionsStr.trim();
            List<String> extensions = CmsStringUtil.splitAsList(validExtensionsStr, EXTENSIONS_SEPARATOR);
            validExtensions = Optional.of(extensions);
        }

        String userForGuestStr = getStringValue(N_USER_FOR_GUEST);
        Optional<CmsUser> userForGuest = Optional.absent();
        if (userForGuestStr != null) {
            userForGuest = Optional.of(m_cms.readUser(userForGuestStr.trim()));
        }

        String projectGroupStr = getStringValue(N_PROJECT_GROUP);
        CmsGroup projectGroup = m_cms.readGroup(projectGroupStr.trim());
        CmsUUID id = configFile.getStructureId();
        CmsUgcConfiguration result = new CmsUgcConfiguration(
            id,
            userForGuest,
            projectGroup,
            resourceType,
            contentPathResource,
            namePattern,
            locale,
            uploadPathResource,
            maxUploadSize,
            maxNumContents,
            queueWaitTime,
            maxQueueLength,
            autoPublish,
            validExtensions);
        result.setPath(configFile.getRootPath());
        return result;
    }
1154289
public function setConfigFile($configFile = '')
    {
        if (!is_readable($configFile)) {
            $this->activeConfig = [];

            throw ParserException::forFileUnreadable($configFile);
        }

        $this->configFile = $configFile;
        if (!$this->parseConfigFile()) {
            throw InvalidConfigException::forEmptyConfig($configFile);
        }

        return $this;
    }
73396
public final void setConfigFile(@Nonnull final String pConfigFile)
    {
        mdlConfigCallable = new CallableNoEx<MdlConfig>()
        {
            @Override
            @Nonnull
            public MdlConfig call()
            {
                MdlConfig result = null;
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(Util.canonize(new File(pConfigFile)));
                    result = activateConfigFile(fis, pConfigFile);
                }
                catch (IllegalArgumentException e) {
                    result = activateConfigFile(null, null);
                    throw e;
                }
                catch (FileNotFoundException e) {
                    result = activateConfigFile(null, null);
                    if (!failQuietly) {
                        throw new IllegalArgumentException(
                            "Config file not found for " + ModuleDirectoryLayoutCheck.class.getSimpleName() + ": "
                                + pConfigFile, e);
                    }
                }
                finally {
                    Util.closeQuietly(fis);
                }
                return result;
            }
        };
    }
463783
def fromConfigFile(filename = DEFAULT_CONFIG_FILE):
    
    parser = SafeConfigParser()
    section = 'fenixedu'
    parser.read(filename)

    client_id = parser.get(section, 'client_id')
    redirect_uri = parser.get(section, 'redirect_uri')
    client_secret = parser.get(section, 'client_secret')

    base_url = parser.get(section, 'base_url')
    api_endpoint = parser.get(section, 'api_endpoint')
    api_version = parser.get(section, 'api_version')

    return FenixEduConfiguration(client_id = client_id,
                                  redirect_uri = redirect_uri,
                                  client_secret = client_secret,
                                  base_url = base_url,
                                  api_endpoint = api_endpoint,
                                  api_version = api_version)
823622
protected function buildActorsForConfig( $configFile ) {
		$config = $this->getGlobalConfig( $configFile );
		$suites = $this->getSuites( $configFile );

		$path = pathinfo( $configFile );
		$dir = isset( $path['dirname'] ) ? $path['dirname'] : getcwd();

		foreach ( $config['include'] as $subConfig ) {
			$this->output->writeln( "<comment>Included Configuration: $subConfig</comment>" );
			$this->buildActorsForConfig( $dir . DIRECTORY_SEPARATOR . $subConfig );
		}

		if ( !empty( $suites ) ) {
			$this->output->writeln( "<info>Building Actor classes for suites: " . implode( ', ', $suites ) . '</info>' );
		}
		foreach ( $suites as $suite ) {
			$settings = $this->getSuiteConfig( $suite, $configFile );
			$gen = new ActorGenerator( $settings );
			$this->output->writeln( '<info>' . Configuration::config()['namespace'] . '\\' . $gen->getActorName() . "</info> includes modules: " . implode( ', ', $gen->getModules() ) );
			$contents = $gen->produce();

			@mkdir( $settings['path'], 0755, true );
			$file = $settings['path'] . $this->getClassName( $settings['class_name'] ) . '.php';
			$this->save( $file, $contents, true );
			$this->output->writeln( "{$settings['class_name']}.php generated successfully. " . $gen->getNumMethods() . " methods added" );
		}
	}
512042
public static function read($sConfigFile)
    {
        $sConfigFile = realpath($sConfigFile);
        if(!is_readable($sConfigFile))
        {
            throw new \Jaxon\Config\Exception\File(jaxon_trans('config.errors.file.access', array('path' => $sConfigFile)));
        }
        $sFileContent = file_get_contents($sConfigFile);
        $aConfigOptions = json_decode($sFileContent, true);
        if(!is_array($aConfigOptions))
        {
            throw new \Jaxon\Config\Exception\File(jaxon_trans('config.errors.file.content', array('path' => $sConfigFile)));
        }

        return $aConfigOptions;
    }
521336
public static function init($configFile='config/settings.yml', $localConfigFile='config/settings.local.yml')
    {
        // Check what php SAPI is being used
        self::$_cli = false;
        if (strcmp(php_sapi_name(), 'cli') === 0)
            self::$_cli = true;

        // Initialize application services, Store application Object as a global
        // Services are available from global app.
        $GLOBALS['app']    = $app = new self();
        $GLOBALS['logger'] = LoggerFactory::instance()->getLogger();
        $GLOBALS['routeLogger'] = LoggerFactory::instance()->getLogger();

        $configFactory     = new ConfigurationFactory($configFile, $localConfigFile);
        $app->_config      = $configFactory->getConfig();
        
        $logFolder =  getcwd().'/logs';
        if (!file_exists($logFolder)) {
            if(!mkdir($logFolder)) {
                $logFolder = sys_get_temp_dir().'/logs';
                if(!file_exists($logFolder) && !mkdir($logFolder)) {
                    die('Insufficient privileges to create logs folder in application directory, or temp path, exiting');    
                }
            }
        }

        $file              = $logFolder.DIRECTORY_SEPARATOR.$app->_config->getApplicationContext().'-debug.log';
        $GLOBALS['logger']->addHandler($file, Logger::ALL, self::$LOG_MAPPING[$app->_config->getLogLevel()]);

        $analyticsFile = $logFolder.DIRECTORY_SEPARATOR.$app->_config->getApplicationContext().'-analytics.log';
        $GLOBALS['routeLogger']->addHandler($analyticsFile, Logger::ALL, self::$LOG_MAPPING[$app->_config->getLogLevel()], 'analytics');

        if (!self::$_cli) {
            $sessionManager = new WebSessionManager();
            $sessionManager->startSession(null, true);
            $app->_services['sessions']   = $sessionManager;

            SecurityUtils::setSecurityManager(new DefaultSecurityManager());

            $app->_subject = $app->_getSubjectFromSession($sessionManager->getActiveSession());

            $app->_services['routing']    = new RoutingEngine();
        }

        $app->_services['messaging']  = NotificationService::instance();

        return $app;
    }
1014428
protected function readConfigurationFile($file)
    {
        if (! file_exists($file)) {
            throw InvalidSetupException::confNotFound($file);
        }
        if (! $json = file_get_contents($file)) {
            throw InvalidSetupException::confNotReadable($file);
        }
        if (! $config = json_decode($json)) {
            throw InvalidSetupException::confNotJson($file);
        }
        sodium_memzero($json);
        return $config;
    }
739154
def get_config(self, configfile):
        
        with open(configfile) as config_file:
            config = json.load(config_file)
        return config
791101
public function get(string $configKey, string $configFile = 'default', ?string $parseType = null)
    {
        $this->load($configFile);
        // check if configs for this file is loaded
        if (!isset($this->data[$configFile])) {
            return false;
        }

        // check if config key is exist
        if (!isset($this->data[$configFile][$configKey])) {
            return false;
        }

        $response = $this->data[$configFile][$configKey];

        // try to convert config value by defined parse type
        $parseType = Str::lowerCase($parseType);
        switch ($parseType) {
            case 'int':
            case 'integer':
                $response = (int)$response;
                break;
            case 'bool':
            case 'boolean':
                $response = (bool)$response;
                break;
            case 'float':
                $response = (float)$response;
                break;
            case 'double':
                $response = (double)$response;
                break;
        }

        return $response;
    }
77705
protected function resolvePath(string $rootPath, string $configFilePath): string
    {
        $file = Path::makeAbsolute($configFilePath, $rootPath);

        if (!file_exists($file)) {
            throw new ConfigException("Config file doesn't exist.");
        }

        return $file;
    }
206585
public function readProjectConfigFile($dir, $configFile)
    {
        $result = null;
        $filename = $dir . '/' . $this->config->get('service.project_config_dir') . '/' . $configFile;
        if (file_exists($filename)) {
            $parser = new Parser();
            $result = $parser->parse(file_get_contents($filename));
        }

        return $result;
    }
451839
public function loadConfigurations(IConfiguration $config, $configFolder, $usePrefix = false) {
        $diretory = new \DirectoryIterator($configFolder);
        foreach($diretory as $fileinfo) {
            if($fileinfo->isDot() ||
                    !$fileinfo->isFile() ||
                    !$fileinfo->isReadable() ||
                    substr($fileinfo->getFilename(), -strlen($this->extension), strlen($this->extension)) != $this->extension) {
                continue;
            }

            $prefix = "";
            if($usePrefix) {
                $prefix = substr($fileinfo->getFilename(), 0, -strlen($this->extension));
            }
            $config->loadFile($fileinfo->getPathname(), $prefix);
        }

        return $config;
    }
903058
public function loadConfig(string $file): self
    {
        if (file_exists($file) === false) {
            throw new \RuntimeException('No such config file.');
        }
        $data = json_decode(file_get_contents($file), true);
        if ($data === null) {
            throw new \RuntimeException('Invalid config file.');
        }
        return $this->setConfigs($data);
    }