3667c88bf25f2c6fcaedb21fb07cb8d19b2c64d1
[rock.divinelegy.git] / Services / StatusReporter.php
1 <?php
2
3 namespace Services;
4
5 use Exception;
6 use Services\Http\IHttpResponse;
7 use Services\IStatusReporter;
8
9 class StatusReporter implements IStatusReporter
10 {
11 private $_message;
12 private $_type;
13 private $_response;
14
15 const ERROR = 'error';
16 const SUCCESS = 'success';
17 const EXCEPTION = 'exception';
18
19 public function __construct(IHttpResponse $response) {
20 $this->_response = $response;
21 }
22
23 public function error($message)
24 {
25 $this->_message = $message;
26 $this->_type = self::ERROR;
27 $this->_response->setHeader('Content-Type', 'application/json')
28 ->setBody($this->json())
29 ->sendResponse();
30 exit();
31 }
32
33 public function success($message)
34 {
35 $this->_message = $message;
36 $this->_type = self::SUCCESS;
37 $this->_response->setHeader('Content-Type', 'application/json')
38 ->setBody($this->json())
39 ->sendResponse();
40 exit();
41 }
42
43 //no need to exit here, exceptions stop the program.
44 public static function exception(Exception $exception)
45 {
46 //we'll be instatic context here so I have to do it this way.
47 header('Content-Type: application/json');
48 echo json_encode(array(self::EXCEPTION => $exception->getMessage()));
49 }
50
51 public function json()
52 {
53 return json_encode(
54 array($this->_type => $this->_message)
55 );
56 }
57 }