]> dev.renevier.net Git - syj.git/blob - application/controllers/helpers/SyjApi.php
display route length
[syj.git] / application / controllers / helpers / SyjApi.php
1 <?php
2 /*  This file is part of Syj, Copyright (c) 2010 Arnaud Renevier,
3     and is published under the AGPL license. */
4
5 class Syj_Controller_Action_Helper_SyjApi extends Zend_Controller_Action_Helper_Abstract
6 {
7     protected $_contentType = 'text/plain';
8     protected $_checkIfNoneMatch = false;
9     protected $_body = '';
10     protected $_code = 200;
11
12     public function init() {
13         $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
14         $viewRenderer->setNoRender();
15         $layout = Zend_Layout::getMvcInstance();
16         if (null !== $layout) {
17             $layout->disableLayout();
18         }
19     }
20
21     public function setContentType($contentType) {
22         $this->_contentType = (string)$contentType;
23         return $this;
24     }
25
26     public function getContentType() {
27         $this->_contentType = $contentType;
28     }
29
30     public function setBodyJson($data) {
31         $this->setBody(json_encode($data))
32              ->setContentType('application/json');
33         return $this;
34     }
35
36     public function setBody($body) {
37         $this->_body = (string)$body;
38         return $this;
39     }
40
41     public function getBody() {
42         return $body;
43     }
44
45     public function setCode($code) {
46         $this->_code = (int)$code;
47         return $this;
48     }
49
50     public function getCode() {
51         return $this->_code;
52     }
53
54     public function setCheckIfNoneMatch($check) {
55         $this->_checkIfNoneMatch = (boolean)$check;
56         return $this;
57     }
58
59     public function getCheckIfNoneMatch() {
60         return $this->_checkIfNoneMatch;
61     }
62
63     public function postDispatch() {
64         $response = $this->getResponse();
65
66         $response->setHeader('Content-Type', $this->_contentType)
67                  ->setHeader('Content-Length', strlen($this->_body));
68
69         if ($this->_checkIfNoneMatch) {
70             $request = $this->getRequest();
71
72             $etag = md5 ($this->_body);
73             if ($request->getServer("HTTP_IF_NONE_MATCH") == $etag) {
74                 $response->setHttpResponseCode(304);
75                 return;
76             }
77
78             // no-cache is needed otherwise IE does not try to get new version.
79             $response->setHeader ('Cache-control', 'no-cache, must-revalidate');
80             $response->setHeader ('Etag', $etag);
81         }
82
83         $response->setHttpResponseCode($this->_code)
84                  ->setBody($this->_body);
85     }
86 }
87 ?>