|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace micro\controllers\rest; |
|
4
|
|
|
|
|
5
|
|
|
use micro\utils\StrUtils; |
|
6
|
|
|
|
|
7
|
|
|
class ResponseFormatter { |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* @param array $datas |
|
11
|
|
|
* @return array |
|
12
|
|
|
*/ |
|
13
|
|
|
public function get($datas){ |
|
14
|
|
|
return $this->format(["datas"=>$datas,"count"=>\sizeof($datas)]); |
|
15
|
|
|
} |
|
16
|
|
|
|
|
17
|
|
|
public function getOne($datas){ |
|
18
|
|
|
return $this->format(["data"=>$datas]); |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Formats a response array |
|
23
|
|
|
* @param array $arrayResponse |
|
24
|
|
|
* @return string |
|
25
|
|
|
*/ |
|
26
|
|
|
public function format($arrayResponse){ |
|
27
|
|
|
return \json_encode($arrayResponse); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
public function getModel($controllerName){ |
|
31
|
|
|
$array=\explode("\\", $controllerName); |
|
32
|
|
|
$result= \ucfirst(end($array)); |
|
33
|
|
|
if(StrUtils::endswith($result, "s")){ |
|
34
|
|
|
$result=\substr($result, 0,-1); |
|
35
|
|
|
} |
|
36
|
|
|
return $result; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
public function toJson($data){ |
|
40
|
|
|
return \json_encode($data); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
public function formatException($e){ |
|
44
|
|
|
return $this->format(["status"=>"error","message"=>\utf8_encode($e->getMessage()),"code"=>@$e->getCode()]); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public static function toXML($data,&$xml_data){ |
|
48
|
|
|
foreach( $data as $key => $value ) { |
|
49
|
|
|
if( is_numeric($key) ){ |
|
50
|
|
|
$key = 'item'.$key; //dealing with <0/>..<n/> issues |
|
51
|
|
|
} |
|
52
|
|
|
if( is_array($value) ) { |
|
53
|
|
|
$subnode = $xml_data->addChild($key); |
|
54
|
|
|
array_to_xml($value, $subnode); |
|
55
|
|
|
} else { |
|
56
|
|
|
$xml_data->addChild("$key",htmlspecialchars("$value")); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|