2 /* This file is part of Syj, Copyright (c) 2010-2011 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 $this->getActionController()->getHelper('SyjNoRender')->disableRender();
17 public function setContentType($contentType) {
18 $this->_contentType = (string)$contentType;
22 public function getContentType() {
23 $this->_contentType = $contentType;
26 public function setBodyJson($data) {
27 $this->setBody(json_encode($data))
28 ->setContentType('application/json');
32 public function setBody($body) {
33 $this->_body = (string)$body;
37 public function getBody() {
41 public function setCode($code) {
42 $this->_code = (int)$code;
46 public function getCode() {
50 public function setRedirect($url, $code = 0) {
51 $this->_redirect = (string)$url;
52 if (is_numeric($code) && (int)$code >= 300 && (int)$code < 400) {
54 } else if (!isset($this->_code)) {
60 public function getRedirect() {
61 return $this->_redirect;
64 public function setCheckIfNoneMatch($check) {
65 $this->_checkIfNoneMatch = (boolean)$check;
69 public function getCheckIfNoneMatch() {
70 return $this->_checkIfNoneMatch;
73 public function postDispatch() {
74 $response = $this->getResponse();
76 $response->setHeader('Content-Type', $this->_contentType, true)
77 ->setHeader('Content-Length', strlen($this->_body), true);
79 if ($this->_checkIfNoneMatch) {
80 $request = $this->getRequest();
82 $etag = md5 ($this->_body);
83 if ($request->getServer("HTTP_IF_NONE_MATCH") == $etag) {
84 $response->setHttpResponseCode(304);
88 // no-cache is needed otherwise IE does not try to get new version.
89 $response->setHeader ('Cache-control', 'no-cache, must-revalidate');
90 $response->setHeader ('Etag', $etag);
93 if ($this->_redirect) {
94 $response->setHeader ('Location', $this->_redirect);
97 $response->setHttpResponseCode($this->_code)
98 ->setBody($this->_body);