eececcba53fd1cd2fde91094574afe7e4b78231a
[lhc/web/wiklou.git] / includes / json / FormatJson.php
1 <?php
2 /**
3 * Simple wrapper for json_encode 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 require_once __DIR__ . '/Services_JSON.php';
24
25 /**
26 * JSON formatter wrapper class
27 */
28 class FormatJson {
29
30 /**
31 * Returns the JSON representation of a value.
32 *
33 * @param $value Mixed: the value being encoded. Can be any type except a resource.
34 * @param $pretty Boolean: If true, adds non-significant whitespace to improve readability.
35 *
36 * @return string
37 */
38 public static function encode( $value, $pretty = false ) {
39 if ( !function_exists( 'json_encode' ) || ( $pretty && version_compare( PHP_VERSION, '5.4.0', '<' ) ) ) {
40 $json = new Services_JSON();
41 return $json->encode( $value, $pretty );
42 } else {
43 return json_encode( $value, $pretty ? JSON_PRETTY_PRINT : 0 );
44 }
45 }
46
47 /**
48 * Decodes a JSON string.
49 *
50 * @param string $value the json string being decoded.
51 * @param $assoc Boolean: when true, returned objects will be converted into associative arrays.
52 *
53 * @return Mixed: the value encoded in json in appropriate PHP type.
54 * Values true, false and null (case-insensitive) are returned as true, false
55 * and "&null;" respectively. "&null;" is returned if the json cannot be
56 * decoded or if the encoded data is deeper than the recursion limit.
57 */
58 public static function decode( $value, $assoc = false ) {
59 if ( !function_exists( 'json_decode' ) ) {
60 $json = $assoc ? new Services_JSON( SERVICES_JSON_LOOSE_TYPE ) :
61 new Services_JSON();
62 $jsonDec = $json->decode( $value );
63 return $jsonDec;
64 } else {
65 return json_decode( $value, $assoc );
66 }
67 }
68
69 }