Revert "merged master"
[lhc/web/wiklou.git] / includes / json / FormatJson.php
1 <?php
2 /**
3 * Simple wrapper for json_econde and json_decode that falls back on Services_JSON class.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 require_once dirname( __FILE__ ) . '/Services_JSON.php';
24
25 /**
26 * JSON formatter wrapper class
27 */
28 class FormatJson {
29
30 /**
31 * Returns the JSON representation of a value.
32 *
33 * @param $value Mixed: the value being encoded. Can be any type except a resource.
34 * @param $isHtml Boolean
35 *
36 * @todo FIXME: "$isHtml" parameter's purpose is not documented. It appears to
37 * map to a parameter labeled "pretty-print output with indents and
38 * newlines" in Services_JSON::encode(), which has no string relation
39 * to HTML output.
40 *
41 * @return string
42 */
43 public static function encode( $value, $isHtml = false ) {
44 if ( !function_exists( 'json_encode' ) || ( $isHtml && version_compare( PHP_VERSION, '5.4.0', '<' ) ) ) {
45 $json = new Services_JSON();
46 return $json->encode( $value, $isHtml );
47 } else {
48 return json_encode( $value, $isHtml ? JSON_PRETTY_PRINT : 0 );
49 }
50 }
51
52 /**
53 * Decodes a JSON string.
54 *
55 * @param $value String: the json string being decoded.
56 * @param $assoc Boolean: when true, returned objects will be converted into associative arrays.
57 *
58 * @return Mixed: the value encoded in json in appropriate PHP type.
59 * Values true, false and null (case-insensitive) are returned as true, false
60 * and "&null;" respectively. "&null;" is returned if the json cannot be
61 * decoded or if the encoded data is deeper than the recursion limit.
62 */
63 public static function decode( $value, $assoc = false ) {
64 if ( !function_exists( 'json_decode' ) ) {
65 $json = $assoc ? new Services_JSON( SERVICES_JSON_LOOSE_TYPE ) :
66 new Services_JSON();
67 $jsonDec = $json->decode( $value );
68 return $jsonDec;
69 } else {
70 return json_decode( $value, $assoc );
71 }
72 }
73
74 }