1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace alkemann\h2l\response; |
4
|
|
|
|
5
|
|
|
use alkemann\h2l\Message; |
6
|
|
|
use alkemann\h2l\Response; |
7
|
|
|
use alkemann\h2l\util\Http; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class Text |
11
|
|
|
* |
12
|
|
|
* @package alkemann\h2l |
13
|
|
|
*/ |
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<string, mixed> $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
|
|
|
/** |
43
|
|
|
* @param string $glue |
44
|
|
|
* @param array<mixed>|\Generator<mixed> $arr |
45
|
|
|
* @return string |
46
|
|
|
*/ |
47
|
|
|
protected static function implode_recur(string $glue, $arr): string |
48
|
|
|
{ |
49
|
|
|
$output = ''; |
50
|
|
|
foreach ($arr as $v) { |
51
|
|
|
if (is_array($v)) { |
52
|
|
|
$output .= static::implode_recur($glue, $v); |
53
|
|
|
} else { |
54
|
|
|
$output .= $glue . $v; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
return $output; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Set header and return a string rendered and ready to be echo'ed as response |
62
|
|
|
* |
63
|
|
|
* Header 'Content-type:' will be set using `header` or an injeced 'header_func' through constructor |
64
|
|
|
* |
65
|
|
|
* @return string |
66
|
|
|
*/ |
67
|
|
|
public function render(): string |
68
|
|
|
{ |
69
|
|
|
$this->setHeaders(); |
70
|
|
|
return $this->message->body(); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|