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

HttpHelper   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 5
eloc 20
c 2
b 0
f 0
dl 0
loc 40
ccs 18
cts 18
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A parseMessage() 0 27 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;
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 42
    public static function parseMessage(string $message): array
28
    {
29 42
        $startLine = null;
30 42
        $headers = [];
31 42
        [$headerLines, $body] = explode(self::BODY_SEPARATOR, $message, 2);
32 42
        $headerLines = explode("\n", $headerLines);
33
34 42
        foreach ($headerLines as $header) {
35
            // Parse message headers
36 42
            if ($startLine === null) {
37 42
                $startLine = explode(' ', $header, 3);
38 42
                continue;
39
            }
40 42
            $parts = explode(':', $header, 2);
41 42
            $key = trim($parts[0]);
42 42
            $value = isset($parts[1]) ? trim($parts[1]) : '';
43
44 42
            if (! isset($headers[$key])) {
45 42
                $headers[$key] = [];
46
            }
47 42
            $headers[$key][] = $value;
48
        }
49
50
        return [
51 42
            (int) ($startLine[1] ?? 0),
52 42
            $headers,
53 42
            $body,
54
        ];
55
    }
56
}
57