/administrator/components/com_zoo/framework/data/json.php

https://gitlab.com/vnsoftdev/amms · PHP · 90 lines · 32 code · 14 blank · 44 comment · 5 complexity · 6f22d0507c8b3ca82b608d19b8dc6316 MD5 · raw file

  1. <?php
  2. /**
  3. * @package com_zoo
  4. * @author YOOtheme http://www.yootheme.com
  5. * @copyright Copyright (C) YOOtheme GmbH
  6. * @license http://www.gnu.org/licenses/gpl.html GNU/GPL
  7. */
  8. /**
  9. * Read and write data in JSON format
  10. *
  11. * @package Framework.Data
  12. */
  13. class JSONData extends AppData {
  14. /**
  15. * If the returned object will be an associative array (default :true)
  16. *
  17. * @var boolean
  18. * @since 1.0.0
  19. */
  20. protected $_assoc = true;
  21. /**
  22. * Class Constructor
  23. *
  24. * @param string|array $data The data to read. Could be either an array or a json string
  25. *
  26. * @since 1.0.0
  27. */
  28. public function __construct($data = array()) {
  29. // decode JSON string
  30. if (is_string($data)) {
  31. $data = json_decode($data, $this->_assoc);
  32. }
  33. parent::__construct($data);
  34. }
  35. /**
  36. * Encode an array or an object in JSON format
  37. *
  38. * @param array|object $data The data to encode
  39. *
  40. * @return string The json encoded string
  41. *
  42. * @since 1.0.0
  43. */
  44. protected function _write($data) {
  45. return $this->_jsonEncode($data);
  46. }
  47. /**
  48. * Do the real json encoding adding human readability. Supports automatic indenting with tabs
  49. *
  50. * @param array|object $in The array or object to encode in json
  51. * @param int $indent The indentation level. Adds $indent tabs to the string
  52. *
  53. * @return string The json encoded string
  54. *
  55. * @since 1.0.0
  56. */
  57. public function _jsonEncode($in, $indent = 0) {
  58. $out = '';
  59. foreach ($in as $key => $value) {
  60. $out .= str_repeat("\t", $indent + 1);
  61. $out .= json_encode((string) $key).': ';
  62. if (is_object($value) || is_array($value)) {
  63. $out .= $this->_jsonEncode($value, $indent + 1);
  64. } else {
  65. $out .= json_encode($value);
  66. }
  67. $out .= ",\n";
  68. }
  69. if (!empty($out)) {
  70. $out = substr($out, 0, -2);
  71. }
  72. $out = " {\n" . $out;
  73. $out .= "\n" . str_repeat("\t", $indent) . "}";
  74. return $out;
  75. }
  76. }