11<?php
2-
32namespace FileManager ;
4-
53class Response {
64 /**
7- * Sends JSON response
8- *
9- * @param $data
10- * @param int $code
11- *
12- * @return mixed
13- */
5+ * Sends JSON response
6+ *
7+ * @param $data
8+ * @param int $code
9+ *
10+ * @return mixed
11+ */
1412 public static function JSON ($ data , $ code =200 )
1513 {
16- header ('Content-Type: application/json ' );
17- http_response_code ($ code );
18- return print_r (json_encode ($ data , 128 ));
19- }
14+ // Clear json_last_error()
15+ json_encode (null );
16+
17+ $ data = self ::convert_from_latin1_to_utf8_recursively ($ data );
18+
19+ $ json = json_encode ($ data , 128 );
20+ if (JSON_ERROR_NONE !== json_last_error ()) {
21+ $ data = new \Exception (sprintf (
22+ 'Unable to encode data to JSON in %s: %s ' ,
23+ __CLASS__ ,
24+ json_last_error_msg ()
25+ ));
26+ http_response_code ('503 ' );
27+ $ json = json_encode (['message ' => $ data ->getMessage ()]);
28+ }else {
29+ http_response_code ($ code );
30+ }
2031
32+ header ('Content-Type: application/json ' );
33+ return print_r ($ json );
34+ }
2135 /**
22- * Sends raw response
23- *
24- * @param $mime
25- * @param $content
26- * @param int $response
27- *
28- * @return bool
29- */
36+ * Sends raw response
37+ *
38+ * @param $mime
39+ * @param $content
40+ * @param int $response
41+ *
42+ * @return bool
43+ */
3044 public static function RAW ($ mime , $ content , $ response =200 )
3145 {
3246 header ('Content-Type: ' . $ mime );
3347 http_response_code ($ response );
3448 print $ content ;
3549 return true ;
3650 }
37- }
51+
52+ /**
53+ * Encode array from latin1 to utf8 recursively
54+ * @param $dat
55+ * @return array|string
56+ */
57+ public static function convert_from_latin1_to_utf8_recursively ($ dat )
58+ {
59+ if (is_string ($ dat )) {
60+ return utf8_encode ($ dat );
61+ } elseif (is_array ($ dat )) {
62+ $ ret = [];
63+ foreach ($ dat as $ i => $ d ) $ ret [ $ i ] = self ::convert_from_latin1_to_utf8_recursively ($ d );
64+ return $ ret ;
65+ } elseif (is_object ($ dat )) {
66+ foreach ($ dat as $ i => $ d ) $ dat ->$ i = self ::convert_from_latin1_to_utf8_recursively ($ d );
67+ return $ dat ;
68+ } else {
69+ return $ dat ;
70+ }
71+ }
72+ }
0 commit comments