1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99:
<?php
namespace Nethgui\Utility;
class HttpResponse
{
private $httpStatusMessages = array(
'200' => 'Success',
'201' => 'Created',
'302' => 'Found',
'400' => 'Bad request',
'403' => 'Forbidden',
'500' => 'Internal server error',
);
public function __construct($content = '', $status = 200, $headers = array())
{
$this->content = $content;
$this->headers = $headers;
$this->status = $status;
$this->eventHandlers = array(
'post-response' => array(),
'pre-response' => array(),
);
}
public function setContent($content)
{
$this->content = $content;
return $this;
}
public function setStatus($status, $message = NULL)
{
if(isset($message)) {
$this->httpStatusMessages[$status] = $message;
}
$this->status = $status;
return $this;
}
public function addHeader($header) {
$this->headers[] = $header;
return $this;
}
public function send()
{
$this->triggerEvent('pre-response');
header(sprintf('HTTP/1.1 %d %s', $this->status, $this->httpStatusMessages[$this->status]));
array_map('header', $this->headers);
echo $this->content;
flush();
$this->triggerEvent('post-response');
}
private function triggerEvent($name)
{
foreach($this->eventHandlers[$name] as $f) {
\call_user_func($f, $this);
}
return $this;
}
public function on($eventName, $handler)
{
$this->eventHandlers[$eventName][] = $handler;
return $this;
}
}