PageRenderTime 23ms CodeModel.GetById 12ms app.highlight 6ms RepoModel.GetById 2ms app.codeStats 0ms

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