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