Passed
Branch master (f36b3c)
by Matthew
08:01
created

Response::send()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 12
c 2
b 1
f 0
dl 0
loc 23
ccs 14
cts 14
cp 1
rs 9.2222
cc 6
nc 12
nop 0
crap 6
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 13
    public static function create($body = '', $code = 200)
30
    {
31 13
        $stream = new Stream('php://memory', 'wb+');
32 13
        $stream->write($body);
33 13
        return (new static)
34 13
            ->withStatus($code)
35 13
            ->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
     */
73 1
    public function send()
74
    {
75 1
        foreach ($this->headers as $key => $value) {
76 1
            header("$key: " . implode(',', $value));
77
        }
78
79 1
        if($this->hasHeader('Content-Type') === false) {
80 1
            header(vsprintf(
81 1
                'Content-Type: %s',
82 1
                $this->hasHeader('Content-Type') ? $this->getHeader('Content-Type') : [$this->contentType]
83 1
            ));
84
        }
85
86 1
        http_response_code($this->getStatusCode());
87
88 1
        if ($this->stream !== null) {
89 1
            if ($this->compression) {
90 1
                ob_start('ob_gzhandler');
91
            }
92 1
            echo (string)$this->getBody();
93
        }
94
95 1
        ob_end_flush();
96
    }
97
98
    /**
99
     * @return string
100
     */
101 1
    public function __toString()
102
    {
103 1
        return (string)$this->getBody();
104
    }
105
}
106