Completed
Push — master ( 1f65a3...0feaa6 )
by Jean-Christophe
01:28
created

ResponseFormatter   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 11
c 0
b 0
f 0
lcom 1
cbo 1
dl 0
loc 54
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 3 1
A getOne() 0 3 1
A format() 0 3 1
A getModel() 0 8 2
A toJson() 0 3 1
A formatException() 0 3 1
A toXML() 0 13 4
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