Skip to content

Instantly share code, notes, and snippets.

@VijayaSankarN
Created July 11, 2017 13:00
Show Gist options
  • Save VijayaSankarN/9e2f9d1a5673a5aef159e2d4108bc8e6 to your computer and use it in GitHub Desktop.
Save VijayaSankarN/9e2f9d1a5673a5aef159e2d4108bc8e6 to your computer and use it in GitHub Desktop.
PHP INI parser with environment based reading
<?php
class Config
{
private static $environments = ['dev', 'qa', 'prod'];
private static $filenames = ['assets', 'libraries'];
private static $filepath = "/";
private static $environment = NULL;
private static $file_data = NULL;
/**
* Get current Environment (default 'dev')
*
* @return string Environment
*/
public static function getEnvironment()
{
if (!isset($_SERVER['APPLICATION_ENV'])) {
$_SERVER['APPLICATION_ENV'] = "dev";
}
if (!in_array($_SERVER['APPLICATION_ENV'], self::$environments)) {
$_SERVER['APPLICATION_ENV'] = "dev";
}
return self::$environment = $_SERVER['APPLICATION_ENV'];
}
/**
* Check the environment
*
* @param string $env Environment to check
*
* @return boolean
*/
public static function isEnvironment($env)
{
return (self::getEnvironment() === $env) ? TRUE : FALSE;
}
/**
* Read / Parse the ini file
*
* @param string $filename
*
* @return array
*/
public static function read($filename)
{
if (is_null(self::$environment)) {
self::getEnvironment();
}
return self::$file_data[$filename] = parse_ini_file(self::$filepath . "$filename." . self::$environment . ".ini", TRUE);
}
/**
* Get value for the key searched for
*
* @param string $search_key
*
* @return string value
*/
public static function get($search_key)
{
$search_key_array = explode('.', $search_key);
if (count($search_key_array) != 3) {
throw new Exception("Invalid search key");
}
list($filename, $section, $key) = $search_key_array;
if (!in_array($filename, self::$filenames)) {
throw new Exception("Invalid file to search");
}
if (is_null(self::$file_data) || !isset(self::$file_data[$filename])) {
self::read($filename);
}
if (self::$file_data === FALSE) {
throw new Exception("File read error");
}
return isset(self::$file_data[$filename][$section][$key]) ? self::$file_data[$filename][$section][$key] : NULL;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment