Response::addHeader()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 2
c 1
b 0
f 1
dl 0
loc 5
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
namespace PlugHttp;
4
5
/**
6
 * Class Response
7
 * @package PlugHttp
8
 */
9
class Response
10
{
11
    /**
12
     * @var array
13
     */
14
    private array $headers;
15
16
    /**
17
     * @var int
18
     */
19
    private int $statusCode;
20
21
    /**
22
     * Response constructor.
23
     */
24
    public function __construct()
25
    {
26
        $this->headers = [];
27
        $this->statusCode = 200;
28
    }
29
30
    /**
31
     * Added several headers.
32
     *
33
     * @param array $headers
34
     * @return $this
35
     */
36
    public function addHeaders(array $headers): Response
37
	{
38
		foreach ($headers as $v) {
39
			$this->headers[] = $v;
40
		}
41
42
		return $this;
43
	}
44
45
    /**
46
     * Added a header.
47
     *
48
     * @param string $header
49
     * @param mixed $value
50
     * @return $this
51
     */
52
    public function addHeader(string $header, $value): Response
53
	{
54
        $this->headers[$header] = $value;
55
56
		return $this;
57
	}
58
59
    /**
60
     * Returns the defined headers.
61
     * @return array
62
     */
63
    public function getHeaders(): array
64
	{
65
		return $this->headers;
66
	}
67
68
    /**
69
     * Set status code.
70
     *
71
     * @param int $statusCode
72
     * @return $this
73
     */
74
    public function setStatusCode(int $statusCode): Response
75
	{
76
		$this->statusCode = $statusCode;
77
78
		return $this;
79
	}
80
81
    /**
82
     * Returns the defined status code.
83
     *
84
     * @return int
85
     */
86
    public function getStatusCode(): int
87
	{
88
		return $this->statusCode;
89
	}
90
91
    /**
92
     * Set all headers.
93
     *
94
     * @return $this
95
     */
96
    public function response(): Response
97
	{
98
		foreach ($this->headers as $k => $v) {
99
			header("{$v}");
100
		}
101
102
		header("HTTP/1.0 {$this->statusCode}");
103
104
		return $this;
105
	}
106
107
    /**
108
     * Return a json and set the header to application/json.
109
     *
110
     * @param array $data
111
     * @return false|string
112
     */
113
    public function json(array $data)
114
	{
115
		header("Content-type: application/json");
116
117
		return json_encode($data);
118
	}
119
}