Browse code

Response class initial feed...

RafaƂ Szklarczyk authored on 16/05/2019 22:17:23
Showing 1 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,73 @@
1
+<?php
2
+
3
+namespace elanpl\L3;
4
+
5
+class Response{
6
+
7
+    protected $headers;
8
+    protected $code;
9
+    protected $reasonPhrase;
10
+    protected $body;
11
+
12
+    public function __construct()
13
+    {
14
+        $this->headers = array();
15
+    }
16
+
17
+    public function getStatusCode(){
18
+        return $this->code;
19
+    }
20
+
21
+    public function getReasonPhrase(){
22
+        return $this->reasonPhrase; 
23
+    }
24
+
25
+    public function getBody(){
26
+        return $this->body;
27
+    }
28
+
29
+    public function withStatus($code, $reasonPhrase = ''){
30
+        $this->code = $code;
31
+        $this->reasonPhrase = $reasonPhrase;
32
+        return $this;
33
+    }
34
+
35
+    public function withHeader($name, $value){
36
+        $this->headers[$name] = $value;
37
+        return $this;
38
+    }
39
+
40
+    public function withBody($body){
41
+        if(is_string($body)){
42
+            $this->body = $body;
43
+        }
44
+        else{
45
+            throw new \Exception('Not implemented!');
46
+        }
47
+        return $this;
48
+    }
49
+
50
+    public function send(){
51
+        if(!headers_sent()){
52
+            if(isset($this->reasonPhrase)&&$this->reasonPhrase!=""){
53
+                header($_SERVER['SERVER_PROTOCOL']." ".$this->code." ".$this->reasonPhrase);
54
+            }
55
+            else if(isset($this->code)) http_response_code($this->code);
56
+            foreach($this->headers as $header => $value){
57
+                header($header.": ".$value);
58
+            }
59
+        }
60
+        if(isset($this->body)) echo $this->body;
61
+    }
62
+
63
+    public function redirect($url, $code=null){
64
+        if(isset($code)){
65
+            http_response_code($code);
66
+        }
67
+        else if(isset($this->code) && $this->code!=''){
68
+            http_response_code($this->code);
69
+        }
70
+        header("Location: ".$url);
71
+    }
72
+
73
+}
0 74
\ No newline at end of file