response.class.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. class Response {
  3. public $output = '';
  4. public $body = '';
  5. private $code = 200;
  6. public $headers = [];
  7. protected $open = true;
  8. public function __construct(){}
  9. public function __toString(){
  10. return $this->body;
  11. }
  12. public function clear(){
  13. if($this->open){
  14. $this->body = '';
  15. }
  16. return $this;
  17. }
  18. public function clear_headers(){
  19. if($this->open){
  20. $this->headers = [];
  21. }
  22. return $this;
  23. }
  24. public function clear_header($name){
  25. foreach($this->headers as $key => $header){
  26. if($header[0] == $name){
  27. array_splice($this->headers, $key, 1);
  28. }
  29. }
  30. return $this;
  31. }
  32. public function write($chunk){
  33. if($this->open){
  34. $this->body .= $chunk;
  35. }
  36. return $this;
  37. }
  38. public function json($json){
  39. if(is_array($json)){
  40. array_walk_recursive($json, function(&$item, $key){
  41. if(!mb_detect_encoding($item, 'utf-8', true)){
  42. $item = utf8_encode($item);
  43. }
  44. });
  45. }
  46. $this->write(json_encode($json));
  47. if(json_last_error() != JSON_ERROR_NONE){
  48. throw new Exception(json_last_error_msg());
  49. }
  50. return $this;
  51. }
  52. public function header($name,$value){
  53. if($this->open){
  54. array_push(
  55. $this->headers,
  56. [
  57. $name,
  58. $value
  59. ]
  60. );
  61. }
  62. return $this;
  63. }
  64. public function redirect($url){
  65. $this->header('Location',Router::url($url));
  66. return $this;
  67. }
  68. public function end($chunk=''){
  69. if($this->open){
  70. $this->write($chunk);
  71. $this->open = false;
  72. }
  73. return $this;
  74. }
  75. public function img($img, $type = false){
  76. if(!$type){
  77. $type = $img->type;
  78. }
  79. $this->clear_header('Content-Type')
  80. ->header('Content-Type', 'image/'.$type);
  81. if(!is_a($img, 'Image')){
  82. $img = new Image(100, 20);
  83. $img->text('Invalid Image',0,0,'black',12);
  84. }
  85. ob_start();
  86. $img();
  87. $this->write(ob_get_contents());
  88. ob_end_clean();
  89. return $this;
  90. }
  91. public function code($code=null){
  92. if(is_null($code)){
  93. return $this->code;
  94. }
  95. $this->code = $code;
  96. return $this;
  97. }
  98. public function shutdown(){
  99. if($this->open){
  100. $this->end();
  101. }
  102. http_response_code($this->code);
  103. foreach($this->headers as $k => $header){
  104. header("{$header[0]}: $header[1]");
  105. }
  106. echo $this->body;
  107. flush();
  108. }
  109. }
  110. ?>