Merge "Add new-inline-tags to tidy.conf"
[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 if ( !defined( 'MEDIAWIKI' ) ) {
24 die( 1 );
25 }
26
27 require_once dirname( __FILE__ ) . '/Services_JSON.php';
28
29 /**
30 * JSON formatter wrapper class
31 */
32 class FormatJson {
33
34 /**
35 * Returns the JSON representation of a value.
36 *
37 * @param $value Mixed: the value being encoded. Can be any type except a resource.
38 * @param $isHtml Boolean
39 *
40 * @todo FIXME: "$isHtml" parameter's purpose is not documented. It appears to
41 * map to a parameter labeled "pretty-print output with indents and
42 * newlines" in Services_JSON::encode(), which has no string relation
43 * to HTML output.
44 *
45 * @return string
46 */
47 public static function encode( $value, $isHtml = false ) {
48 // Some versions of PHP have a broken json_encode, see PHP bug
49 // 46944. Test encoding an affected character (U+20000) to
50 // avoid this.
51 if ( !function_exists( 'json_encode' ) || $isHtml || strtolower( json_encode( "\xf0\xa0\x80\x80" ) ) != '"\ud840\udc00"' ) {
52 $json = new Services_JSON();
53 return $json->encode( $value, $isHtml );
54 } else {
55 return json_encode( $value );
56 }
57 }
58
59 /**
60 * Decodes a JSON string.
61 *
62 * @param $value String: the json string being decoded.
63 * @param $assoc Boolean: when true, returned objects will be converted into associative arrays.
64 *
65 * @return Mixed: the value encoded in json in appropriate PHP type.
66 * Values true, false and null (case-insensitive) are returned as true, false
67 * and &null; respectively. &null; is returned if the json cannot be
68 * decoded or if the encoded data is deeper than the recursion limit.
69 */
70 public static function decode( $value, $assoc = false ) {
71 if ( !function_exists( 'json_decode' ) ) {
72 $json = $assoc ? new Services_JSON( SERVICES_JSON_LOOSE_TYPE ) :
73 new Services_JSON();
74 $jsonDec = $json->decode( $value );
75 return $jsonDec;
76 } else {
77 return json_decode( $value, $assoc );
78 }
79 }
80
81 }