HttpResponse::encodeHeaders()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 11

Duplication

Lines 21
Ratio 100 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
dl 21
loc 21
ccs 11
cts 11
cp 1
rs 9.3142
c 0
b 0
f 0
cc 3
eloc 11
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Dazzle\Http\Http;
4
5
use Dazzle\Http\NetworkMessageInterface;
6
use GuzzleHttp\Psr7\Response;
7
8 View Code Duplication
class HttpResponse extends Response implements HttpResponseInterface, NetworkMessageInterface
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
9
{
10
    /**
11
     * @override
12
     * @inheritDoc
13
     */
14 1
    public function __toString()
15
    {
16 1
        return $this->encode();
17
    }
18
19
    /**
20
     * @override
21
     * @inheritDoc
22
     */
23 3
    public function encode()
24
    {
25 3
        return sprintf(
26 3
            "HTTP/%s %d %s\r\n%s\r\n%s",
27 3
            $this->getProtocolVersion(),
28 3
            $this->getStatusCode(),
29 3
            $this->getReasonPhrase(),
30 3
            $this->encodeHeaders($this->getHeaders()),
31 3
            (string) $this->getBody()
32
        );
33
    }
34
35
    /**
36
     * @override
37
     * @inheritDoc
38
     */
39 2
    public function read()
40
    {
41 2
        return (string) $this->getBody();
42
    }
43
44
    /**
45
     * Encode headers.
46
     *
47
     * @param string[][] $headers
48
     * @return string
49
     */
50 4
    protected function encodeHeaders($headers = [])
51
    {
52 4
        $data = '';
53
54 4
        foreach ($headers as $name=>$values)
55
        {
56 4
            $temp = [];
57 4
            $data .= $name . ": ";
58 4
            $values = (array) $values;
59
60 4
            foreach ($values as $value)
61
            {
62 4
                $temp[] = $this->encodeHeader($value);
63
            }
64
65 4
            $data .= implode(", ", $temp);
66 4
            $data .= "\r\n";
67
        }
68
69 4
        return $data;
70
    }
71
72
    /**
73
     * Encode single header.
74
     *
75
     * @param string $header
76
     * @return string
77
     */
78 5
    protected function encodeHeader($header)
79
    {
80 5
        return preg_replace_callback(
81 5
            '/(?:[^A-Za-z0-9_\-\.~!\$&\'\(\)\[\]\*\+,:;=\/% ]+|%(?![A-Fa-f0-9]{2}))/',
82 5
            function (array $matches) {
83
                return rawurlencode($matches[0]);
84 5
            },
85 5
            $header
86
        );
87
    }
88
}
89