]> dev.renevier.net Git - syj.git/blob - application/controllers/helpers/SyjApi.php
redirection after path creation is decided by server (php), not guessed by client...
[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     }
34
35     public function setBody($body) {
36         $this->_body = (string)$body;
37         return $this;
38     }
39
40     public function getBody() {
41         return $body;
42     }
43
44     public function setCode($code) {
45         $this->_code = (int)$code;
46         return $this;
47     }
48
49     public function getCode() {
50         return $this->_code;
51     }
52
53     public function setCheckIfNoneMatch($check) {
54         $this->_checkIfNoneMatch = (boolean)$check;
55         return $this;
56     }
57
58     public function getCheckIfNoneMatch() {
59         return $this->_checkIfNoneMatch;
60     }
61
62     public function postDispatch() {
63         $response = $this->getResponse();
64
65         $response->setHeader('Content-Type', $this->_contentType)
66                  ->setHeader('Content-Length', strlen($this->_body));
67
68         if ($this->_checkIfNoneMatch) {
69             $request = $this->getRequest();
70
71             $etag = md5 ($this->_body);
72             if ($request->getServer("HTTP_IF_NONE_MATCH") == $etag) {
73                 $response->setHttpResponseCode(304);
74                 return;
75             }
76
77             // no-cache is needed otherwise IE does not try to get new version.
78             $response->setHeader ('Cache-control', 'no-cache, must-revalidate');
79             $response->setHeader ('Etag', $etag);
80         }
81
82         $response->setHttpResponseCode($this->_code)
83                  ->setBody($this->_body);
84     }
85 }
86 ?>