JsonFormatter.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 JsonFormatter implements FormatterInterface
  10. {
  11. /** @var array */
  12. private $config;
  13. public function __construct(array $config = [])
  14. {
  15. $this->config = $config + [
  16. 'file_extension' => '.json',
  17. 'encode_options' => 0,
  18. 'decode_assoc' => true
  19. ];
  20. }
  21. /**
  22. * @deprecated 1.5 Use $formatter->getDefaultFileExtension() instead.
  23. */
  24. public function getFileExtension()
  25. {
  26. return $this->getDefaultFileExtension();
  27. }
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function getDefaultFileExtension()
  32. {
  33. $extensions = $this->getSupportedFileExtensions();
  34. return (string) reset($extensions);
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. public function getSupportedFileExtensions()
  40. {
  41. return (array) $this->config['file_extension'];
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function encode($data)
  47. {
  48. $encoded = @json_encode($data, $this->config['encode_options']);
  49. if ($encoded === false) {
  50. throw new \RuntimeException('Encoding JSON failed');
  51. }
  52. return $encoded;
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function decode($data)
  58. {
  59. $decoded = @json_decode($data, $this->config['decode_assoc']);
  60. if ($decoded === false) {
  61. throw new \RuntimeException('Decoding JSON failed');
  62. }
  63. return $decoded;
  64. }
  65. }