JsonFormatter.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 JsonFormatter extends AbstractFormatter
  12. {
  13. public function __construct(array $config = [])
  14. {
  15. $config += [
  16. 'file_extension' => '.json',
  17. 'encode_options' => 0,
  18. 'decode_assoc' => true,
  19. 'decode_depth' => 512,
  20. 'decode_options' => 0
  21. ];
  22. parent::__construct($config);
  23. }
  24. /**
  25. * Returns options used in encode() function.
  26. *
  27. * @return int
  28. */
  29. public function getEncodeOptions(): int
  30. {
  31. return $this->getConfig('encode_options');
  32. }
  33. /**
  34. * Returns options used in decode() function.
  35. *
  36. * @return int
  37. */
  38. public function getDecodeOptions(): int
  39. {
  40. return $this->getConfig('decode_options');
  41. }
  42. /**
  43. * Returns recursion depth used in decode() function.
  44. *
  45. * @return int
  46. */
  47. public function getDecodeDepth(): int
  48. {
  49. return $this->getConfig('decode_depth');
  50. }
  51. /**
  52. * Returns true if JSON objects will be converted into associative arrays.
  53. *
  54. * @return bool
  55. */
  56. public function getDecodeAssoc(): bool
  57. {
  58. return $this->getConfig('decode_assoc');
  59. }
  60. /**
  61. * {@inheritdoc}
  62. * @see FileFormatterInterface::encode()
  63. */
  64. public function encode($data): string
  65. {
  66. $encoded = @json_encode($data, $this->getEncodeOptions());
  67. if ($encoded === false && json_last_error() !== JSON_ERROR_NONE) {
  68. throw new \RuntimeException('Encoding JSON failed: ' . json_last_error_msg());
  69. }
  70. return $encoded;
  71. }
  72. /**
  73. * {@inheritdoc}
  74. * @see FileFormatterInterface::decode()
  75. */
  76. public function decode($data)
  77. {
  78. $decoded = @json_decode($data, $this->getDecodeAssoc(), $this->getDecodeDepth(), $this->getDecodeOptions());
  79. if (null === $decoded && json_last_error() !== JSON_ERROR_NONE) {
  80. throw new \RuntimeException('Decoding JSON failed: ' . json_last_error_msg());
  81. }
  82. return $decoded;
  83. }
  84. }