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

HttpHelper::responseContentAsArray()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 21
ccs 0
cts 12
cp 0
rs 9.6111
c 0
b 0
f 0
cc 5
nc 5
nop 2
crap 30
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
    public static function parseMessage(string $message): array
28
    {
29
        $startLine = null;
30
        $headers = [];
31
        [$headerLines, $body] = explode(self::BODY_SEPARATOR, $message, 2);
32
        $headerLines = explode("\n", $headerLines);
33
34
        foreach ($headerLines as $header) {
35
            // Parse message headers
36
            if ($startLine === null) {
37
                $startLine = explode(' ', $header, 3);
38
                continue;
39
            }
40
            $parts = explode(':', $header, 2);
41
            $key = trim($parts[0]);
42
            $value = isset($parts[1]) ? trim($parts[1]) : '';
43
44
            if (! isset($headers[$key])) {
45
                $headers[$key] = [];
46
            }
47
            $headers[$key][] = $value;
48
        }
49
50
        return [
51
            (int) ($startLine[1] ?? 0),
52
            $headers,
53
            $body,
54
        ];
55
    }
56
}
57