config.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php namespace System;
  2. class Config {
  3. /**
  4. * All of the loaded configuration items.
  5. *
  6. * @var array
  7. */
  8. private static $items = array();
  9. /**
  10. * Get a configuration item.
  11. *
  12. * @param string $key
  13. * @return mixed
  14. */
  15. public static function get($key)
  16. {
  17. list($file, $key) = static::parse($key);
  18. static::load($file);
  19. return (array_key_exists($key, static::$items[$file])) ? static::$items[$file][$key] : null;
  20. }
  21. /**
  22. * Set a configuration item.
  23. *
  24. * @param string $key
  25. * @param mixed $value
  26. * @return void
  27. */
  28. public static function set($file, $value)
  29. {
  30. list($file, $key) = static::parse($key);
  31. static::load($file);
  32. static::$items[$file][$key] = $value;
  33. }
  34. /**
  35. * Parse a configuration key.
  36. *
  37. * @param string $key
  38. * @return array
  39. */
  40. private static function parse($key)
  41. {
  42. $segments = explode('.', $key);
  43. if (count($segments) < 2)
  44. {
  45. throw new \Exception("Invalid configuration key [$key].");
  46. }
  47. return array($segments[0], implode('.', array_slice($segments, 1)));
  48. }
  49. /**
  50. * Load all of the configuration items.
  51. *
  52. * @param string $file
  53. * @return void
  54. */
  55. public static function load($file)
  56. {
  57. if (array_key_exists($file, static::$items))
  58. {
  59. return;
  60. }
  61. if ( ! file_exists($path = APP_PATH.'config/'.$file.EXT))
  62. {
  63. throw new \Exception("Configuration file [$file] does not exist.");
  64. }
  65. static::$items[$file] = require $path;
  66. }
  67. }