Passed
Push — master ( c88722...fc87d6 )
by Alexander
01:38
created

Text::implode_recur()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
c 0
b 0
f 0
nc 3
nop 2
dl 0
loc 10
rs 10
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 $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
60
    {
61
        $this->setHeaders();
62
        return $this->message->body();
63
    }
64
}
65