Completed
Push — master ( 588b5e...a331b6 )
by Matthew
04:08
created

Response::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4286
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
namespace Fyuze\Http;
3
4
use Fyuze\Http\Message\Response as PsrResponse;
5
use Fyuze\Http\Message\Stream;
6
7
class Response extends PsrResponse
8
{
9
    /**
10
     * @var string
11
     */
12
    protected $contentType = 'text/html';
13
14
    /**
15
     * @var boolean
16
     */
17
    protected $cache = false;
18
19
    /**
20
     * @var boolean
21
     */
22
    protected $compression = true;
23
24
    /**
25
     * @param $body
26
     * @param $code
27
     * @return Response
28
     */
29 12
    public static function create($body = '', $code = 200)
30
    {
31 12
        $stream = new Stream('php://memory', 'wb+');
32 12
        $stream->write($body);
33 12
        return (new static)
34 12
            ->withStatus($code)
35 12
            ->withBody($stream);
36
    }
37
38
    /**
39
     * Set response caching, blank for default
40
     *
41
     * @param boolean $value
42
     * @return bool
43
     */
44 1
    public function setCache($value = false)
45
    {
46 1
        return $this->cache = $value;
47
    }
48
49
    /**
50
     * Set output compression, blank for default
51
     *
52
     * @param boolean $value
53
     * @return bool
54
     */
55 1
    public function setCompression($value = true)
56
    {
57 1
        return $this->compression = $value;
58
    }
59
60
    /**
61
     * Modify the response
62
     *
63
     * @param \Closure $closure
64
     */
65 1
    public function modify(\Closure $closure)
66
    {
67 1
        return $this->stream = $closure($this->stream);
68
    }
69
70
    /**
71
     * Sends the response
72
     * We ignore coverage here because
73
     * headers cannot be tested in cli sapi
74
     *
75
     * @codeCoverageIgnore
76
     */
77
    public function send()
78
    {
79
        header('Content-Type: ' . $this->contentType);
80
81
        foreach ($this->headers as $key => $value) {
82
            header("$key: $value");
83
        }
84
85
        http_response_code($this->getStatusCode());
86
87
        if ($this->stream !== null) {
88
            if ($this->compression) {
89
                ob_start('ob_gzhandler');
90
            }
91
            echo (string) $this;
92
        }
93
    }
94
95
    /**
96
     * @return string
97
     */
98 2
    public function __toString()
99
    {
100 2
        return (string)$this->getBody();
101
    }
102
}
103