Response::contentType()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace alkemann\h2l;
4
5
use alkemann\h2l\util\Http;
6
7
/**
8
 * Abstract class Response
9
 *
10
 * @package alkemann\h2l
11
 */
12
abstract class Response
13
{
14
    /**
15
     * @var array<string, mixed>
16
     */
17
    protected array $config = [];
18
    /**
19
     * @var Message
20
     */
21
    protected Message $message;
22
23
    /**
24
     * Returns the HTTP Code of the response
25
     *
26
     * @return int
27
     */
28
    public function code(): int
29
    {
30
        return $this->message->code();
31
    }
32
33
    /**
34
     * Returns the content type of the messe part of the response
35
     *
36
     * @return string
37
     */
38
    public function contentType(): string
39
    {
40
        return $this->message->contentType();
41
    }
42
43
    /**
44
     * Returns the `alkemann\Message` object part of the response
45
     *
46
     * @return null|Message
47
     */
48
    public function message(): ?Message
49
    {
50
        return $this->message;
51
    }
52
53
    /**
54
     * @throws \Error if the configured `header_func` is not callable
55
     */
56
    protected function setHeaders(): void
57
    {
58
        $h = $this->config['header_func'] ?? 'header';
59
        if (is_callable($h) === false) {
60
            throw new \Error("header_func is not callable");
61
        }
62
        $code = $this->message->code();
63
        if ($code != Http::CODE_OK) {
64
            $msg = Http::httpCodeToMessage($code);
65
            $h("HTTP/1.1 {$code} {$msg}");
66
        }
67
68
        foreach ($this->message->headers() as $name => $value) {
69
            $h("{$name}: $value");
70
        }
71
    }
72
73
    /**
74
     * Shorthand for rendering the Response object
75
     *
76
     * Returns the result of calling Response::render()
77
     */
78
    public function __toString(): string
79
    {
80
        return $this->render();
81
    }
82
83
    /**
84
     * All subclasses of Response must implement render to return the string body
85
     *
86
     * @return string
87
     */
88
    abstract public function render(): string;
89
}
90