Response   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 77
rs 10
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A code() 0 3 1
A message() 0 3 1
A contentType() 0 3 1
A setHeaders() 0 14 4
A __toString() 0 3 1
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