1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ubiquity\controllers\rest; |
4
|
|
|
|
5
|
|
|
use Ubiquity\utils\base\UString; |
6
|
|
|
|
7
|
|
|
class ResponseFormatter { |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* @param array $datas |
11
|
|
|
* @return string |
12
|
|
|
*/ |
13
|
1 |
|
public function get($datas){ |
14
|
1 |
|
$datas=$this->getDatas($datas); |
15
|
1 |
|
return $this->format(["datas"=>$datas,"count"=>\sizeof($datas)]); |
16
|
|
|
} |
17
|
|
|
|
18
|
1 |
|
public function getDatas($datas){ |
19
|
|
|
$datas=\array_map(function($o){ |
20
|
1 |
|
return $this->cleanRestObject($o); |
21
|
1 |
|
}, $datas); |
22
|
1 |
|
return \array_values($datas); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function getJSONDatas($datas){ |
26
|
|
|
return $this->toJson($this->getDatas($datas)); |
27
|
|
|
} |
28
|
|
|
|
29
|
1 |
|
public function cleanRestObject($o){ |
30
|
1 |
|
$o=$o->_rest; |
31
|
1 |
|
foreach ($o as $k=>$v){ |
32
|
1 |
|
if(isset($v->_rest)) |
33
|
1 |
|
$o[$k]=$v->_rest; |
34
|
1 |
|
if(\is_array($v)){ |
35
|
1 |
|
foreach ($v as $index=>$values){ |
36
|
1 |
|
if(isset($values->_rest)) |
37
|
1 |
|
$v[$index]=$this->cleanRestObject($values); |
38
|
|
|
} |
39
|
1 |
|
$o[$k]=$v; |
40
|
|
|
} |
41
|
|
|
} |
42
|
1 |
|
return $o; |
43
|
|
|
} |
44
|
|
|
|
45
|
1 |
|
public function getOne($datas){ |
46
|
1 |
|
return $this->format(["data"=>$this->cleanRestObject($datas)]); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Formats a response array |
51
|
|
|
* @param array $arrayResponse |
52
|
|
|
* @return string |
53
|
|
|
*/ |
54
|
1 |
|
public function format($arrayResponse){ |
55
|
1 |
|
return \json_encode($arrayResponse); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
public function getModel($controllerName){ |
59
|
|
|
$array=\explode("\\", $controllerName); |
60
|
|
|
$result= \ucfirst(end($array)); |
61
|
|
|
if(UString::endswith($result, "s")){ |
62
|
|
|
$result=\substr($result, 0,-1); |
63
|
|
|
} |
64
|
|
|
return $result; |
65
|
|
|
} |
66
|
|
|
|
67
|
1 |
|
public function toJson($data){ |
68
|
1 |
|
return \json_encode($data); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
public function formatException($e){ |
72
|
|
|
return $this->format(["status"=>"error","message"=>\utf8_encode($e->getMessage()),"code"=>@$e->getCode()]); |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
public static function toXML($data,&$xml_data){ |
76
|
|
|
foreach( $data as $key => $value ) { |
77
|
|
|
if( is_numeric($key) ){ |
78
|
|
|
$key = 'item'.$key; //dealing with <0/>..<n/> issues |
79
|
|
|
} |
80
|
|
|
if( is_array($value) ) { |
81
|
|
|
$subnode = $xml_data->addChild($key); |
82
|
|
|
self::toXML($value, $subnode); |
83
|
|
|
} else { |
84
|
|
|
$xml_data->addChild("$key",htmlspecialchars("$value")); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|