Ubiquity  2.0.3
php rapid development framework
ResponseFormatter.php
Go to the documentation of this file.
1 <?php
2 
4 
6 
8 
13  public function get($datas){
14  $datas=$this->getDatas($datas);
15  return $this->format(["datas"=>$datas,"count"=>\sizeof($datas)]);
16  }
17 
18  public function getDatas($datas){
19  $datas=\array_map(function($o){
20  return $this->cleanRestObject($o);
21  }, $datas);
22  return \array_values($datas);
23  }
24 
25  public function getJSONDatas($datas){
26  return $this->toJson($this->getDatas($datas));
27  }
28 
29  public function cleanRestObject($o){
30  $o=$o->_rest;
31  foreach ($o as $k=>$v){
32  if(isset($v->_rest))
33  $o[$k]=$v->_rest;
34  if(\is_array($v)){
35  foreach ($v as $index=>$values){
36  if(isset($values->_rest))
37  $v[$index]=$this->cleanRestObject($values);
38  }
39  $o[$k]=$v;
40  }
41  }
42  return $o;
43  }
44 
45  public function getOne($datas){
46  return $this->format(["data"=>$this->cleanRestObject($datas)]);
47  }
48 
54  public function format($arrayResponse){
55  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  public function toJson($data){
68  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  array_to_xml($value, $subnode);
83  } else {
84  $xml_data->addChild("$key",htmlspecialchars("$value"));
85  }
86  }
87  }
88 }
format($arrayResponse)
Formats a response array.
static endswith($hay, $needle)
Definition: UString.php:16