Response.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace yiins\web;
  3. class Response extends \CApplicationComponent
  4. {
  5. const FORMAT_RAW = 'raw';
  6. const FORMAT_HTML = 'html';
  7. const FORMAT_JSON = 'json';
  8. const FORMAT_JSONP = 'jsonp';
  9. const FORMAT_XML = 'xml';
  10. public $format = self::FORMAT_HTML;
  11. /**
  12. * @var ResponseFilterInterface[]
  13. */
  14. public $filters = [];
  15. protected $_result;
  16. protected $isSent = false;
  17. public function init()
  18. {
  19. parent::init();
  20. }
  21. public function setResult($value)
  22. {
  23. $this->_result = $value;
  24. }
  25. public function setStatusCode($value)
  26. {
  27. header('HTTP/1.1 ' . $value);
  28. }
  29. /**
  30. * Sends the response to the client.
  31. */
  32. public function send()
  33. {
  34. if ($this->isSent) {
  35. return;
  36. }
  37. $this->prepare();
  38. $this->sendContent();
  39. $this->isSent = true;
  40. }
  41. protected function prepare()
  42. {
  43. if ($this->format === static::FORMAT_JSON) {
  44. header('Content-type: application/json; charset=utf-8');
  45. $this->_result = \CJSON::encode($this->_result);
  46. }
  47. if ($this->format === static::FORMAT_XML) {
  48. header('Content-type: application/xml; charset=utf-8');
  49. }
  50. if ($this->format === static::FORMAT_RAW) {
  51. header('Content-type: text/plain; charset=utf-8');
  52. }
  53. foreach ($this->filters as $filter) {
  54. if ($filter instanceof ResponseFilterInterface) {
  55. $this->_result = $filter->process($this->_result);
  56. }
  57. }
  58. }
  59. protected function sendContent()
  60. {
  61. echo trim($this->_result);
  62. }
  63. }