Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
7 / 7 |
|
100.00% |
4 / 4 |
CRAP | |
100.00% |
1 / 1 |
| Response | |
100.00% |
7 / 7 |
|
100.00% |
4 / 4 |
7 | |
100.00% |
1 / 1 |
| clearHeaders | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| setHeader | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| header | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
| send | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
3 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace Dynart\Micro; |
| 4 | |
| 5 | /** |
| 6 | * Represents the HTTP response |
| 7 | * @package Dynart\Micro |
| 8 | */ |
| 9 | class Response { |
| 10 | |
| 11 | /** |
| 12 | * Stores the headers for the response |
| 13 | * @var array |
| 14 | */ |
| 15 | protected $headers = []; |
| 16 | |
| 17 | /** |
| 18 | * Clears the headers |
| 19 | */ |
| 20 | public function clearHeaders(): void { |
| 21 | $this->headers = []; |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * Sets a header for the response |
| 26 | * |
| 27 | * @param string $name The name of the header |
| 28 | * @param string $value The value of the header |
| 29 | */ |
| 30 | public function setHeader(string $name, string $value): void { |
| 31 | $this->headers[$name] = $value; |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * Returns with a header value by name |
| 36 | * |
| 37 | * @param string $name The header name |
| 38 | * @param string|null $default The default value if the header doesn't present |
| 39 | * @return string|null The header value or default |
| 40 | */ |
| 41 | public function header(string $name, $default = null) { |
| 42 | return array_key_exists($name, $this->headers) ? $this->headers[$name] : $default; |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * Sends the headers then the given body content |
| 47 | * |
| 48 | * @param string $content The body content of the response |
| 49 | */ |
| 50 | public function send($content = ''): void { |
| 51 | $sendHeaderFunction = function_exists('header') ? function ($n, $v) { header($n.': '.$v); } : function($n, $v) {}; // because of CLI |
| 52 | foreach ($this->headers as $name => $value) { |
| 53 | $sendHeaderFunction($name, $value); |
| 54 | } |
| 55 | echo $content; |
| 56 | } |
| 57 | } |