Completed
Push — master ( a03880...647009 )
by Marcel
03:55
created

RequestSerializer   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 3
dl 0
loc 60
ccs 26
cts 26
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A serialize() 0 4 1
A requestLine() 0 8 1
A headers() 0 21 3
A fixTarget() 0 12 2
1
<?php
2
3
namespace UMA\Psr7Hmac\Internal;
4
5
use Psr\Http\Message\RequestInterface;
6
7
final class RequestSerializer
8
{
9
    const CRLF = "\r\n";
10
11
    /**
12
     * Returns the string representation of an HTTP request.
13
     *
14
     * @param RequestInterface $request Request to convert to a string.
15
     *
16
     * @return string
17
     */
18 136
    public static function serialize(RequestInterface $request)
19
    {
20 136
        return self::requestLine($request).self::headers($request).$request->getBody();
21
    }
22
23 136
    private static function requestLine(RequestInterface $request)
24
    {
25 136
        $method = $request->getMethod();
26 136
        $target = self::fixTarget(trim($request->getRequestTarget()));
27 136
        $protocol = 'HTTP/'.$request->getProtocolVersion();
28
29 136
        return "$method $target $protocol".self::CRLF;
30
    }
31
32 136
    private static function headers(RequestInterface $request)
33
    {
34 136
        $headers = $request->getHeaders();
35
36 136
        unset($headers['host']);
37 136
        unset($headers['Host']);
38
39 136
        $headerLines = [];
40 136
        foreach ($headers as $name => $value) {
41 127
            $value = is_array($value) ? $value : [$value];
42 127
            $normalizedName = (new HeaderNameNormalizer())->normalize($name);
43
44 127
            $headerLines[$normalizedName] = $normalizedName.': '.implode(',', $value).self::CRLF;
45 136
        }
46
47 136
        ksort($headerLines);
48
49 136
        $host = $request->getUri()->getHost();
50
51 136
        return "host: $host".self::CRLF.implode($headerLines).self::CRLF;
52
    }
53
54 136
    private static function fixTarget($target)
55
    {
56 136
        if (!array_key_exists('query', $parsedTarget = parse_url($target))) {
57 118
            return $target;
58
        }
59
60 18
        parse_str($parsedTarget['query'], $query);
61
62 18
        ksort($query);
63
64 18
        return $parsedTarget['path'].'?'.http_build_query($query);
65
    }
66
}
67