IniFile.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace RocketTheme\Toolbox\File;
  3. /**
  4. * Implements INI File reader.
  5. *
  6. * @package RocketTheme\Toolbox\File
  7. * @author RocketTheme
  8. * @license MIT
  9. */
  10. class IniFile extends File
  11. {
  12. /**
  13. * @var string
  14. */
  15. protected $extension = '.ini';
  16. /**
  17. * @var array|File[]
  18. */
  19. static protected $instances = [];
  20. /**
  21. * Check contents and make sure it is in correct format.
  22. *
  23. * @param array $var
  24. * @return array
  25. * @throws \RuntimeException
  26. */
  27. protected function check($var)
  28. {
  29. if (!is_array($var)) {
  30. throw new \RuntimeException('Provided data is not an array');
  31. }
  32. return $var;
  33. }
  34. /**
  35. * Encode configuration object into RAW string (INI).
  36. *
  37. * @param array $var
  38. * @return string
  39. * @throws \RuntimeException
  40. */
  41. protected function encode($var)
  42. {
  43. $string = '';
  44. foreach ($var as $key => $value) {
  45. $string .= $key . '="' . preg_replace(
  46. ['/"/', '/\\\/', "/\t/", "/\n/", "/\r/"],
  47. ['\"', '\\\\', '\t', '\n', '\r'],
  48. $value
  49. ) . "\"\n";
  50. }
  51. return $string;
  52. }
  53. /**
  54. * Decode INI file into contents.
  55. *
  56. * @param string $var
  57. * @return array
  58. * @throws \RuntimeException
  59. */
  60. protected function decode($var)
  61. {
  62. $decoded = file_exists($this->filename) ? @parse_ini_file($this->filename) : [];
  63. if ($decoded === false) {
  64. throw new \RuntimeException("Decoding file '{$this->filename}' failed'");
  65. }
  66. return $decoded;
  67. }
  68. }