Completed
Pull Request — master (#25)
by Alexander
01:37
created

Json::setHeaders()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
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 Json
11
 *
12
 * @package alkemann\h2l
13
 */
14
class Json extends Response
15
{
16
    public function __construct($content = null, int $code = Http::CODE_OK, array $config = [])
17
    {
18
        $this->config = $config;
19
        $this->message = (new Message())
20
            ->withCode($code)
21
            ->withHeaders([
22
                'Content-Type' => Http::CONTENT_JSON
23
            ])
24
            ->withBody($this->encodeAndContainData($content))
25
        ;
26
    }
27
28
    /**
29
     * Set header and return a string rendered and ready to be echo'ed as response
30
     *
31
     * Header 'Content-type:' will be set using `header` or an injeced 'header_func' through constructor
32
     */
33
    public function render(): string
34
    {
35
        $this->setHeaders();
36
        return $this->message->body();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->message->body() could return the type null which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
37
    }
38
39
    private function encodeAndContainData($content): string
40
    {
41
        if (empty($content)) {
42
            return "";
43
        }
44
        if ($content instanceof \Generator) {
45
            $content = iterator_to_array($content);
46
        }
47
        return json_encode(['data' => $content]);
48
    }
49
}
50