| Total Complexity | 8 |
| Total Lines | 49 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 14 | class Text extends Response |
||
| 15 | { |
||
| 16 | /** |
||
| 17 | * @param mixed $content Content to render, arrays will be joined by newline, everything else cast to string |
||
| 18 | * @param int $code HTTP code to respond with, defaults to `200` |
||
| 19 | * @param array $config inject config/overrides like `header_func` |
||
| 20 | */ |
||
| 21 | public function __construct($content, int $code = Http::CODE_OK, array $config = []) |
||
| 22 | { |
||
| 23 | switch (true) { |
||
| 24 | case is_string($content): |
||
| 25 | // passthrough |
||
| 26 | break; |
||
| 27 | case is_array($content) || $content instanceof \Generator: |
||
| 28 | $content = trim(static::implode_recur("\n", $content), "\n"); |
||
| 29 | break; |
||
| 30 | default: |
||
| 31 | $content = (string) $content; |
||
| 32 | break; |
||
| 33 | } |
||
| 34 | $this->config = $config; |
||
| 35 | $this->message = (new Message()) |
||
| 36 | ->withCode($code) |
||
| 37 | ->withHeaders(['Content-Type' => Http::CONTENT_TEXT]) |
||
| 38 | ->withBody($content) |
||
| 39 | ; |
||
| 40 | } |
||
| 41 | |||
| 42 | protected static function implode_recur($glue, $arr){ |
||
| 43 | $output = ''; |
||
| 44 | foreach ($arr as $v) { |
||
| 45 | if (is_array($v)) { |
||
| 46 | $output .= static::implode_recur($glue, $v); |
||
| 47 | } else { |
||
| 48 | $output .= $glue . $v; |
||
| 49 | } |
||
| 50 | } |
||
| 51 | return $output; |
||
| 52 | } |
||
| 53 | |||
| 54 | /** |
||
| 55 | * Set header and return a string rendered and ready to be echo'ed as response |
||
| 56 | * |
||
| 57 | * Header 'Content-type:' will be set using `header` or an injeced 'header_func' through constructor |
||
| 58 | */ |
||
| 59 | public function render(): string |
||
| 63 | } |
||
| 64 | } |
||
| 65 |