More biz to help simfiles make it. Better error reporting service.
[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 $_messages = array();
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 = null)
24 {
25 if($message) $this->addMessage($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 = null)
34 {
35 if($message) $this->addMessage($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 public function addMessage($message)
44 {
45 $this->_messages[] = $message;;
46 }
47
48 //no need to exit here, exceptions stop the program.
49 public static function exception(Exception $exception)
50 {
51 //we'll be instatic context here so I have to do it this way.
52 header('Content-Type: application/json');
53 echo json_encode(array(
54 'status' => self::EXCEPTION,
55 'messages' => array($exception->getMessage())));
56 }
57
58 public function json()
59 {
60 return json_encode(
61 array(
62 'status' => $this->_type,
63 'messages' => $this->_messages)
64 );
65 }
66 }