1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ByJG\RestServer; |
4
|
|
|
|
5
|
|
|
use ByJG\Serialize\Formatter\JsonFormatter; |
6
|
|
|
use ByJG\Serialize\Formatter\XmlFormatter; |
7
|
|
|
|
8
|
|
|
class ServiceHandler implements HandlerInterface |
9
|
|
|
{ |
10
|
|
|
|
11
|
|
|
protected $output = Output::JSON; |
12
|
|
|
|
13
|
|
|
public function getOutput() |
14
|
|
|
{ |
15
|
|
|
return $this->output; |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
public function setOutput($output) |
19
|
|
|
{ |
20
|
|
|
// Check if output is set |
21
|
|
|
if ($output != Output::JSON && $output != Output::XML) { |
22
|
|
|
throw new \Exception('Invalid output format. Valid are XML or JSON'); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
$this->output = $output; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function setHeader() |
29
|
|
|
{ |
30
|
|
|
switch ($this->getOutput()) { |
31
|
|
|
case Output::JSON: |
32
|
|
|
header('Content-Type: application/json'); |
33
|
|
|
break; |
34
|
|
|
|
35
|
|
|
case Output::XML: |
36
|
|
|
header('Content-Type: text/xml'); |
37
|
|
|
break; |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* CORS - Better do that in your http server, but you can enable calling this |
43
|
|
|
*/ |
44
|
|
|
public function setHeaderCors() |
|
|
|
|
45
|
|
|
{ |
46
|
|
|
header('Access-Control-Allow-Origin: *'); |
47
|
|
|
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method"); |
48
|
|
|
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE"); |
49
|
|
|
$method = $_SERVER['REQUEST_METHOD']; |
50
|
|
|
if ($method == "OPTIONS") { |
51
|
|
|
return false; |
52
|
|
|
} |
53
|
|
|
return true; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public function execute(ServiceAbstract $instance) |
57
|
|
|
{ |
58
|
|
|
|
59
|
|
|
$serialized = $instance->getResponse()->getResponseBag()->process(); |
60
|
|
|
|
61
|
|
|
switch ($this->getOutput()) { |
62
|
|
|
case Output::JSON: |
63
|
|
|
return (new JsonFormatter())->process($serialized); |
64
|
|
|
|
65
|
|
|
case Output::XML: |
66
|
|
|
return (new XmlFormatter())->process($serialized); |
67
|
|
|
|
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return null; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: