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