HttpParser::parseRequest()   B
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 14
cts 14
cp 1
rs 8.5906
c 0
b 0
f 0
cc 5
eloc 14
nc 5
nop 1
crap 5
1
<?php
2
3
namespace Dazzle\Http\Http\Driver\Parser;
4
5
use Dazzle\Throwable\Exception\Logic\InvalidArgumentException;
6
use Dazzle\Http\Http\HttpRequest;
7
use Dazzle\Http\Http\HttpResponse;
8
use GuzzleHttp\Psr7;
9
10
class HttpParser implements HttpParserInterface
11
{
12
    /**
13
     * @override
14
     * @inheritDoc
15
     */
16 6
    public function parseRequest($message)
17
    {
18 6
        $data = Psr7\_parse_message($message);
19 6
        $matches = [];
20
21 6
        if (!preg_match('/^[a-zA-Z]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches))
22
        {
23 2
            throw new InvalidArgumentException('Invalid request string');
24
        }
25
26 4
        $parts = explode(' ', $data['start-line'], 3);
27 4
        $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1';
28
29 4
        $request = new HttpRequest(
30 4
            $parts[0],
31 4
            $matches[1] === '/' ? Psr7\_parse_request_uri($parts[1], $data['headers']) : $parts[1],
32 4
            $data['headers'],
33 4
            $data['body'],
34 4
            $version
35
        );
36
37 4
        return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]);
38
    }
39
40
    /**
41
     * @override
42
     * @inheritDoc
43
     */
44 1
    public function parseResponse($message)
45
    {
46 1
        $data = Psr7\_parse_message($message);
47
48 1
        if (!preg_match('/^HTTP\/.* [0-9]{3} .*/', $data['start-line']))
49
        {
50
            throw new InvalidArgumentException('Invalid response string');
51
        }
52 1
        $parts = explode(' ', $data['start-line'], 3);
53
54 1
        return new HttpResponse(
55 1
            $parts[1],
56 1
            $data['headers'],
57 1
            $data['body'],
58 1
            explode('/', $parts[0])[1],
59 1
            isset($parts[2]) ? $parts[2] : null
60
        );
61
    }
62
}
63