IniFormatter.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * @package Grav\Framework\File\Formatter
  4. *
  5. * @copyright Copyright (C) 2015 - 2018 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Framework\File\Formatter;
  9. class IniFormatter implements FormatterInterface
  10. {
  11. /** @var array */
  12. private $config;
  13. /**
  14. * IniFormatter constructor.
  15. * @param array $config
  16. */
  17. public function __construct(array $config = [])
  18. {
  19. $this->config = $config + [
  20. 'file_extension' => '.ini'
  21. ];
  22. }
  23. /**
  24. * @deprecated 1.5 Use $formatter->getDefaultFileExtension() instead.
  25. */
  26. public function getFileExtension()
  27. {
  28. return $this->getDefaultFileExtension();
  29. }
  30. /**
  31. * {@inheritdoc}
  32. */
  33. public function getDefaultFileExtension()
  34. {
  35. $extensions = $this->getSupportedFileExtensions();
  36. return (string) reset($extensions);
  37. }
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public function getSupportedFileExtensions()
  42. {
  43. return (array) $this->config['file_extension'];
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function encode($data)
  49. {
  50. $string = '';
  51. foreach ($data as $key => $value) {
  52. $string .= $key . '="' . preg_replace(
  53. ['/"/', '/\\\/', "/\t/", "/\n/", "/\r/"],
  54. ['\"', '\\\\', '\t', '\n', '\r'],
  55. $value
  56. ) . "\"\n";
  57. }
  58. return $string;
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function decode($data)
  64. {
  65. $decoded = @parse_ini_string($data);
  66. if ($decoded === false) {
  67. throw new \RuntimeException('Decoding INI failed');
  68. }
  69. return $decoded;
  70. }
  71. }