HeaderValidator::validateHeaderValueMatchRfc()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 4
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Furious\Psr7\Header;
6
7
use Furious\Psr7\Exception\InvalidArgumentException;
8
use function preg_match;
9
use function is_string;
10
use function is_array;
11
use function is_numeric;
12
13
final class HeaderValidator
14
{
15
    public function validate(string $header, $values): void
16
    {
17
        $this->validateHeaderMatchRfc($header);
18
19
        if (!is_array($values)) {
20
            $this->validateHeaderValueMatchRfc($values);
21
            return;
22
        }
23
24
        $this->validateHeaderValuesEmpty($values);
25
26
        foreach ($values as $value) {
27
            $this->validateHeaderValueMatchRfc($value);
28
        }
29
    }
30
31
    // Validate
32
33
    private function validateHeaderMatchRfc(string $header): void
34
    {
35
        if (!$this->matchHeaderRfc($header)) {
36
            throw new InvalidArgumentException('Header name must be an RFC 7230 compatible string.');
37
        }
38
    }
39
40
    private function validateHeaderValueMatchRfc($value): void
41
    {
42
        if (
43
            (!is_numeric($value) and !is_string($value))
44
            or !$this->matchHeaderValuesRfc((string) $value)
45
        ) {
46
            throw new InvalidArgumentException('Header values must be RFC 7230 compatible strings.');
47
        }
48
    }
49
50
    private function validateHeaderValuesEmpty($values): void
51
    {
52
        if (empty($values)) {
53
            throw new InvalidArgumentException('Header values must be a string or an array of strings, empty array given.');
54
        }
55
    }
56
57
    // Match
58
59
    private function matchHeaderRfc(string $header): bool
60
    {
61
        return boolval(preg_match("@^[!#$&%'+*.^_`|~0-9A-Za-z-]+$@", $header));
62
    }
63
64
    private function matchHeaderValuesRfc(string $values): bool
65
    {
66
        return boolval(preg_match("@^[ \t\x21-\x7E\x80-\xFF]*$@", $values));
67
    }
68
}