IniFormatter.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @package Grav\Framework\File\Formatter
  5. *
  6. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  7. * @license MIT License; see LICENSE file for details.
  8. */
  9. namespace Grav\Framework\File\Formatter;
  10. use Grav\Framework\File\Interfaces\FileFormatterInterface;
  11. class IniFormatter extends AbstractFormatter
  12. {
  13. /**
  14. * IniFormatter constructor.
  15. * @param array $config
  16. */
  17. public function __construct(array $config = [])
  18. {
  19. $config += [
  20. 'file_extension' => '.ini'
  21. ];
  22. parent::__construct($config);
  23. }
  24. /**
  25. * {@inheritdoc}
  26. * @see FileFormatterInterface::encode()
  27. */
  28. public function encode($data): string
  29. {
  30. $string = '';
  31. foreach ($data as $key => $value) {
  32. $string .= $key . '="' . preg_replace(
  33. ['/"/', '/\\\/', "/\t/", "/\n/", "/\r/"],
  34. ['\"', '\\\\', '\t', '\n', '\r'],
  35. $value
  36. ) . "\"\n";
  37. }
  38. return $string;
  39. }
  40. /**
  41. * {@inheritdoc}
  42. * @see FileFormatterInterface::decode()
  43. */
  44. public function decode($data): array
  45. {
  46. $decoded = @parse_ini_string($data);
  47. if ($decoded === false) {
  48. throw new \RuntimeException('Decoding INI failed');
  49. }
  50. return $decoded;
  51. }
  52. }