| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <?php
- namespace yiins\web;
- class Response extends \CApplicationComponent
- {
- const FORMAT_RAW = 'raw';
- const FORMAT_HTML = 'html';
- const FORMAT_JSON = 'json';
- const FORMAT_JSONP = 'jsonp';
- const FORMAT_XML = 'xml';
- public $format = self::FORMAT_HTML;
- /**
- * @var ResponseFilterInterface[]
- */
- public $filters = [];
- protected $_result;
- protected $isSent = false;
- public function init()
- {
- parent::init();
- }
- public function setResult($value)
- {
- $this->_result = $value;
- }
- public function setStatusCode($value)
- {
- header('HTTP/1.1 ' . $value);
- }
- /**
- * Sends the response to the client.
- */
- public function send()
- {
- if ($this->isSent) {
- return;
- }
- $this->prepare();
- $this->sendContent();
- $this->isSent = true;
- }
- protected function prepare()
- {
- if ($this->format === static::FORMAT_JSON) {
- header('Content-type: application/json; charset=utf-8');
- $this->_result = \CJSON::encode($this->_result);
- }
- if ($this->format === static::FORMAT_XML) {
- header('Content-type: application/xml; charset=utf-8');
- }
- if ($this->format === static::FORMAT_RAW) {
- header('Content-type: text/plain; charset=utf-8');
- }
- foreach ($this->filters as $filter) {
- if ($filter instanceof ResponseFilterInterface) {
- $this->_result = $filter->process($this->_result);
- }
- }
- }
- protected function sendContent()
- {
- echo trim($this->_result);
- }
- }
|