Boolean parameters suck, but we can make them suck less by adding constants you can...
[lhc/web/wiklou.git] / includes / json / FormatJson.php
1 <?php
2
3 if ( !defined( 'MEDIAWIKI' ) ) {
4 die( 1 );
5 }
6
7 /**
8 * Simple wrapper for json_econde and json_decode that falls back on Services_JSON class
9 */
10 class FormatJson {
11
12 // Constants for decode() return types
13 const AS_OBJECT = true;
14 const AS_ARRAY = false;
15
16 /**
17 * Turn an array or object into a JSON string
18 * @param $value Mixed. Array or object to turn into JSON
19 * @param $isHtml bool ???
20 * @return <type>
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 * Decode some JSON into an array or object
36 * @param $value String of Json
37 * @param $assoc bool One of AS_OBJECT or AS_ARRAY to specify return type
38 * @return Array or Object
39 */
40 public static function decode( $value, $assoc = false ) {
41 if ( !function_exists( 'json_decode' ) ) {
42 $json = new Services_JSON();
43 $jsonDec = $json->decode( $value );
44 if( $assoc ) {
45 $jsonDec = wfObjectToArray( $jsonDec );
46 }
47 return $jsonDec;
48 } else {
49 return json_decode( $value, $assoc );
50 }
51 }
52 }