Responding   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 16
dl 0
loc 42
c 0
b 0
f 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A makeResponse() 0 21 4
A __construct() 0 3 1
1
<?php
2
/**
3
 * HTTP Encoder
4
 * User: moyo
5
 * Date: 08/01/2018
6
 * Time: 4:04 PM
7
 */
8
9
namespace Carno\HTTP\Powered\Native\Parser;
10
11
use Psr\Http\Message\ResponseInterface;
12
13
class Responding
14
{
15
    private const LENGTH = 'Content-length';
16
17
    /**
18
     * @var string
19
     */
20
    private $socket = null;
21
22
    /**
23
     * Encoder constructor.
24
     * @param Protocol $socket
25
     */
26
    public function __construct(Protocol $socket)
27
    {
28
        $this->socket = $socket;
0 ignored issues
show
Documentation Bug introduced by
It seems like $socket of type Carno\HTTP\Powered\Native\Parser\Protocol is incompatible with the declared type string of property $socket.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
29
    }
30
31
    /**
32
     * @param ResponseInterface $response
33
     */
34
    public function makeResponse(ResponseInterface $response) : void
35
    {
36
        $lines[] = sprintf(
0 ignored issues
show
Comprehensibility Best Practice introduced by
$lines was never initialized. Although not strictly required by PHP, it is generally a good practice to add $lines = array(); before regardless.
Loading history...
37
            'HTTP/%s %d %s',
38
            $response->getProtocolVersion(),
39
            $response->getStatusCode(),
40
            $response->getReasonPhrase()
41
        );
42
43
        if (!$response->hasHeader(self::LENGTH)) {
44
            $response->withHeader(self::LENGTH, $response->getBody()->getSize());
45
        }
46
47
        foreach ($response->getHeaders() as $name => $values) {
48
            $lines[] = sprintf('%s: %s', $name, implode(',', $values));
49
        }
50
51
        $this->socket->write(implode(Protocol::CRLF, $lines).Protocol::SPLIT);
52
53
        if ($response->getBody()->getSize() > 0) {
54
            $this->socket->write((string)$response->getBody());
55
        }
56
    }
57
}
58