/
service.php
107 lines (85 loc) · 2.6 KB
/
service.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
include 'host.php';
try {
$request = new Request();
$request->process();
} catch (Exception $e) {
header("Status: 401");
print $e->getMessage();
}
class Request
{
private $class;
private $method;
private $id;
private $content_type;
public function __construct()
{
foreach (array('class', 'method', 'id') as $key) {
if (array_key_exists($key, $_REQUEST)) {
$this->$key = $_REQUEST[$key];
}
}
switch ($_SERVER['HTTP_ACCEPT']) {
case 'text/javascript':
case 'application/json':
$this->content_type = 'json';
break;
case 'text/xml':
default:
$this->content_type = 'xml';
break;
}
}
public function process()
{
if (!class_exists($this->class)) {
throw new Exception("Service class does not exist");
}
if (!method_exists($this->class, $this->method)) {
throw new Exception("Serivce {$this->class} method does not exist");
}
$obj = new $this->class();
if (isset($this->id)) {
$obj->$this->method($this->id);
}
$data = call_user_func(array($obj, $this->method));
$this->output($data);
}
private function output($data)
{
switch ($this->content_type) {
case 'json':
$this->outputJSON($data);
break;
case 'xml':
default:
$this->outputXML($data);
break;
}
}
private function outputXML($data)
{
$root_name = strtolower($this->class) . "-" . strtolower($this->method);
$dom = new DOMDocument('1.0', 'iso-8859-1');
$root = $dom->createElement($root_name, '');
foreach ($data as $values) {
$element = $dom->createElement(strtolower($this->class), '');
foreach ($values as $prop => $prop_value) {
$prop_element = $dom->createElement($prop, $prop_value);
$element->appendChild($prop_element);
}
$root->appendChild($element);
}
$dom->appendChild($root);
header("Content-Type:text/xml");
echo $dom->saveXML();
}
private function outputJSON($data)
{
// The Json header has been removed to extract correctly the data
// because the mechanism for extracting json data no includes a header
header("Content-Type:text/javascript");
echo json_encode($data);
}
}