HeaderFactory::fromString()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 9
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 13
ccs 9
cts 9
cp 1
crap 4
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stadly\Http\Header\Common;
6
7
use Stadly\Http\Exception\InvalidHeader;
8
use Stadly\Http\Utilities\Rfc7230;
9
10
/**
11
 * Class for generating HTTP header fields.
12
 */
13
final class HeaderFactory
14
{
15
    /**
16
     * Construct header from string.
17
     *
18
     * @param string $header Header field string.
19
     * @return Header Header generated based on the string.
20
     * @throws InvalidHeader If the header is invalid.
21
     */
22 22
    public static function fromString(string $header): Header
23
    {
24 22
        $regEx = '{^' . Rfc7230::HEADER_FIELD_CAPTURE . '$}';
25 22
        $plainHeader = mb_convert_encoding($header, 'ISO-8859-1', 'UTF-8');
26 22
        if ($plainHeader !== $header || preg_match($regEx, $header, $matches) !== 1) {
27 3
            throw new InvalidHeader('Invalid header field: ' . $header);
28
        }
29
30 19
        switch (strtolower($matches['FIELD_NAME'])) {
31 19
            case 'content-type':
32 3
                return ContentType::fromValue($matches['FIELD_VALUE']);
33
            default:
34 16
                return new ArbitraryHeader($matches['FIELD_NAME'], $matches['FIELD_VALUE']);
35
        }
36
    }
37
}
38