Ubiquity  2.0.0
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=\array_map(function($o){
15  return $this->cleanRestObject($o);
16  }, $datas);
17  $datas=\array_values($datas);
18  return $this->format(["datas"=>$datas,"count"=>\sizeof($datas)]);
19  }
20 
21  public function cleanRestObject($o){
22  $o=$o->_rest;
23  foreach ($o as $k=>$v){
24  if(isset($v->_rest))
25  $o[$k]=$v->_rest;
26  if(\is_array($v)){
27  foreach ($v as $index=>$values){
28  if(isset($values->_rest))
29  $v[$index]=$this->cleanRestObject($values);
30  }
31  $o[$k]=$v;
32  }
33  }
34  return $o;
35  }
36 
37  public function getOne($datas){
38  return $this->format(["data"=>$this->cleanRestObject($datas)]);
39  }
40 
46  public function format($arrayResponse){
47  return \json_encode($arrayResponse);
48  }
49 
50  public function getModel($controllerName){
51  $array=\explode("\\", $controllerName);
52  $result= \ucfirst(end($array));
53  if(UString::endswith($result, "s")){
54  $result=\substr($result, 0,-1);
55  }
56  return $result;
57  }
58 
59  public function toJson($data){
60  return \json_encode($data);
61  }
62 
63  public function formatException($e){
64  return $this->format(["status"=>"error","message"=>\utf8_encode($e->getMessage()),"code"=>@$e->getCode()]);
65  }
66 
67  public static function toXML($data,&$xml_data){
68  foreach( $data as $key => $value ) {
69  if( is_numeric($key) ){
70  $key = 'item'.$key; //dealing with <0/>..<n/> issues
71  }
72  if( is_array($value) ) {
73  $subnode = $xml_data->addChild($key);
74  array_to_xml($value, $subnode);
75  } else {
76  $xml_data->addChild("$key",htmlspecialchars("$value"));
77  }
78  }
79  }
80 }
format($arrayResponse)
Formats a response array.
static endswith($hay, $needle)
Definition: UString.php:16