2 /* This file is part of Syj, Copyright (c) 2010 Arnaud Renevier,
3 and is published under the AGPL license. */
5 class Syj_Controller_Action_Helper_SyjApi extends Zend_Controller_Action_Helper_Abstract
7 protected $_contentType = 'text/plain';
8 protected $_checkIfNoneMatch = false;
10 protected $_code = 200;
11 protected $_redirect = '';
13 public function init() {
14 $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
15 $viewRenderer->setNoRender();
16 $layout = Zend_Layout::getMvcInstance();
17 if (null !== $layout) {
18 $layout->disableLayout();
22 public function setContentType($contentType) {
23 $this->_contentType = (string)$contentType;
27 public function getContentType() {
28 $this->_contentType = $contentType;
31 public function setBodyJson($data) {
32 $this->setBody(json_encode($data))
33 ->setContentType('application/json');
37 public function setBody($body) {
38 $this->_body = (string)$body;
42 public function getBody() {
46 public function setCode($code) {
47 $this->_code = (int)$code;
51 public function getCode() {
55 public function setRedirect($url, $code = 0) {
56 $this->_redirect = (string)$url;
57 if (is_numeric($code) && (int)$code >= 300 && (int)$code < 400) {
59 } else if (!isset($this->_code)) {
65 public function getRedirect() {
66 return $this->_redirect;
69 public function setCheckIfNoneMatch($check) {
70 $this->_checkIfNoneMatch = (boolean)$check;
74 public function getCheckIfNoneMatch() {
75 return $this->_checkIfNoneMatch;
78 public function postDispatch() {
79 $response = $this->getResponse();
81 $response->setHeader('Content-Type', $this->_contentType)
82 ->setHeader('Content-Length', strlen($this->_body));
84 if ($this->_checkIfNoneMatch) {
85 $request = $this->getRequest();
87 $etag = md5 ($this->_body);
88 if ($request->getServer("HTTP_IF_NONE_MATCH") == $etag) {
89 $response->setHttpResponseCode(304);
93 // no-cache is needed otherwise IE does not try to get new version.
94 $response->setHeader ('Cache-control', 'no-cache, must-revalidate');
95 $response->setHeader ('Etag', $etag);
98 if ($this->_redirect) {
99 $response->setHeader ('Location', $this->_redirect);
102 $response->setHttpResponseCode($this->_code)
103 ->setBody($this->_body);