* Added file description headers
[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 * @file
6 */
7
8 if ( !defined( 'MEDIAWIKI' ) ) {
9 die( 1 );
10 }
11
12 class FormatJson {
13
14 /**
15 * Returns the JSON representation of a value.
16 *
17 * @param $value Mixed: the value being encoded. Can be any type except a resource.
18 * @param $isHtml Boolean
19 *
20 * @return string
21 */
22 public static function encode( $value, $isHtml = false ) {
23 // Some versions of PHP have a broken json_encode, see PHP bug
24 // 46944. Test encoding an affected character (U+20000) to
25 // avoid this.
26 if ( !function_exists( 'json_encode' ) || $isHtml || strtolower( json_encode( "\xf0\xa0\x80\x80" ) ) != '\ud840\udc00' ) {
27 $json = new Services_JSON();
28 return $json->encode( $value, $isHtml );
29 } else {
30 return json_encode( $value );
31 }
32 }
33
34 /**
35 * Decodes a JSON string.
36 *
37 * @param $value String: the json string being decoded.
38 * @param $assoc Boolean: when true, returned objects will be converted into associative arrays.
39 *
40 * @return Mixed: the value encoded in json in appropriate PHP type.
41 * Values true, false and null (case-insensitive) are returned as true, false
42 * and &null; respectively. &null; is returned if the json cannot be
43 * decoded or if the encoded data is deeper than the recursion limit.
44 */
45 public static function decode( $value, $assoc = false ) {
46 if ( !function_exists( 'json_decode' ) ) {
47 $json = new Services_JSON();
48 $jsonDec = $json->decode( $value );
49 if( $assoc ) {
50 $jsonDec = wfObjectToArray( $jsonDec );
51 }
52 return $jsonDec;
53 } else {
54 return json_decode( $value, $assoc );
55 }
56 }
57
58 }