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