Passed
Pull Request — master (#7)
by Sandro
02:03
created

HttpHelper::parseMessage()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 27
ccs 18
cts 18
cp 1
rs 9.3554
c 0
b 0
f 0
cc 5
nc 6
nop 1
crap 5
1
<?php
2
/**
3
 * Sandro Keil (https://sandro-keil.de)
4
 *
5
 * @link      http://github.com/sandrokeil/arangodb-php-client for the canonical source repository
6
 * @copyright Copyright (c) 2018-2019 Sandro Keil
7
 * @license   http://github.com/sandrokeil/arangodb-php-client/blob/master/LICENSE.md New BSD License
8
 */
9
10
declare(strict_types=1);
11
12
namespace ArangoDb\Http;
13
14
final class HttpHelper
15
{
16
    /**
17
     * Separator between header and body
18
     */
19
    private const BODY_SEPARATOR = "\r\n\r\n";
20
21
    /**
22
     * Splits the message in HTTP status code, headers and body.
23
     *
24
     * @param string $message
25
     * @return array Values are HTTP status code, PSR-7 headers and body
26
     */
27 40
    public static function parseMessage(string $message): array
28
    {
29 40
        $startLine = null;
30 40
        $headers = [];
31 40
        [$headerLines, $body] = explode(self::BODY_SEPARATOR, $message, 2);
32 40
        $headerLines = explode("\n", $headerLines);
33
34 40
        foreach ($headerLines as $header) {
35
            // Parse message headers
36 40
            if ($startLine === null) {
37 40
                $startLine = explode(' ', $header, 3);
38 40
                continue;
39
            }
40 40
            $parts = explode(':', $header, 2);
41 40
            $key = trim($parts[0]);
42 40
            $value = isset($parts[1]) ? trim($parts[1]) : '';
43
44 40
            if (! isset($headers[$key])) {
45 40
                $headers[$key] = [];
46
            }
47 40
            $headers[$key][] = $value;
48
        }
49
50
        return [
51 40
            (int) ($startLine[1] ?? 0),
52 40
            $headers,
53 40
            $body,
54
        ];
55
    }
56
}
57