Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 0a4fbbe

Browse files
committedOct 28, 2012
Fixes #14869: Provide a simple API for outputting JSON
1 parent 2193b5c commit 0a4fbbe

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
 

‎core/json_api.php

+71
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@
2727
* requires url_api
2828
*/
2929
require_once( 'url_api.php' );
30+
require_once( 'database_api.php' );
31+
require_once( 'lang_api.php' );
3032

3133
/**
3234
* Get a chunk of JSON from a given URL.
@@ -44,3 +46,72 @@ function json_url( $p_url, $p_member = null ) {
4446
return $t_json->$p_member;
4547
}
4648
}
49+
50+
/**
51+
* JSON error handler
52+
*
53+
* <p>Ensures that all necessary headers are set and terminates processing after being invoked.</p>
54+
*/
55+
function json_error_handler( $p_type, $p_error, $p_file, $p_line, $p_context ) {
56+
# flush any language overrides to return to user's natural default
57+
if( function_exists( 'db_is_connected' ) ) {
58+
if( db_is_connected() ) {
59+
lang_push( lang_get_default() );
60+
}
61+
}
62+
63+
# build an appropriate error string
64+
switch( $p_type ) {
65+
case E_WARNING:
66+
$t_error_type = 'SYSTEM WARNING';
67+
$t_error_description = $p_error;
68+
break;
69+
case E_NOTICE:
70+
$t_error_type = 'SYSTEM NOTICE';
71+
$t_error_description = $p_error;
72+
break;
73+
case E_USER_ERROR:
74+
$t_error_type = "APPLICATION ERROR #$p_error";
75+
$t_error_description = error_string( $p_error );
76+
break;
77+
case E_USER_WARNING:
78+
$t_error_type = "APPLICATION WARNING #$p_error";
79+
$t_error_description = error_string( $p_error );
80+
break;
81+
case E_USER_NOTICE:
82+
# used for debugging
83+
$t_error_type = 'DEBUG';
84+
$t_error_description = $p_error;
85+
break;
86+
default:
87+
#shouldn't happen, just display the error just in case
88+
$t_error_type = '';
89+
$t_error_description = $p_error;
90+
}
91+
92+
json_output_raw(array(
93+
'status' => 'ERROR',
94+
'type' => $t_error_type,
95+
'contents' => $t_error_description
96+
));
97+
}
98+
/**
99+
* Outputs the specified contents inside a json response with OK status
100+
*
101+
* <p>Ensures that all necessary headers are set and terminates processing.</p>
102+
* @param string $contents The contents to encode
103+
*/
104+
function json_output_response ( $contents = '') {
105+
106+
json_output_raw( array(
107+
'status' => 'OK',
108+
'contents' => $contents
109+
) );
110+
}
111+
112+
function json_output_raw( $contents ) {
113+
114+
header('Content-Type: application/json');
115+
echo json_encode( $contents );
116+
exit();
117+
}

0 commit comments

Comments
 (0)
Please sign in to comment.