*/ abstract class ResponseAbstract implements ResponseInterface, ServiceLocatorAwareInterface { use ServiceLocatorAwareTrait; /** * http response code * @var integer */ protected $httpCode; /** * content type to use into response header * @var string */ protected $contentType = ''; /** * Allowed methods for 405 response * @var string[] */ protected $allowMethodsHeader; /** * @var Exception */ protected $exception; protected $rendererClassList = [ 'html' => 'HtmlResponse', 'json' => 'JsonResponse', 'none' => 'NonAcceptable', 'ajax' => 'AjaxResponse', ]; /** * search rendering method in function of request accept header * @param array $accept * @return ResponseAbstract */ protected function chooseRenderer(array $accept) { $renderClass = 'none'; foreach ($accept as $mimeType) { switch (trim(strtolower($mimeType))) { case 'text/html': case 'application/xhtml+xml': case '*/*': $renderClass = 'html'; break 2; case 'application/json': case 'text/json': $renderClass = 'json'; break 2; } } if (tao_helpers_Request::isAjax()) { $renderClass = 'ajax'; } $className = __NAMESPACE__ . '\\' . $this->rendererClassList[$renderClass]; $renderer = new $className(); return $renderer->setServiceLocator($this->getServiceLocator()); } /** * send headers * @return $this */ protected function sendHeaders() { $context = Context::getInstance(); $context->getResponse()->setContentHeader($this->contentType); header(HTTPToolkit::statusCodeHeader($this->httpCode)); if (!empty($this->allowMethodsHeader)) { header('Allow: ' . implode(', ', $this->allowMethodsHeader)); } return $this; } /** * set response http status code * @param int $code * @return $this */ public function setHttpCode($code) { $this->httpCode = $code; return $this; } /** * @param string[]|null $allowedMethods * @return $this */ public function setAllowedMethods($allowedMethods) { $this->allowMethodsHeader = $allowedMethods; return $this; } /** * @inherit */ public function send() { $accept = array_key_exists('HTTP_ACCEPT', $_SERVER) ? explode(',', $_SERVER['HTTP_ACCEPT']) : []; $renderer = $this->chooseRenderer($accept); return $renderer ->setException($this->exception) ->setHttpCode($this->httpCode) ->setAllowedMethods($this->allowMethodsHeader) ->sendHeaders() ->send(); } /** * @inherit */ public function trace() { if ($this->exception) { common_Logger::singleton()->handleException($this->exception); } return $this; } /** * set up exception * @param Exception $exception * @return $this */ public function setException(Exception $exception) { $this->exception = $exception; return $this; } }