aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/bakame/http-structured-fields/src/Key.php
blob: e1971426a218cc218aa98a2deda3a342e261ce0b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php

namespace Bakame\Http\StructuredFields;

use Stringable;

use function preg_match;

/**
 * @see https://www.rfc-editor.org/rfc/rfc9651.html#section-3.1.2
 * @internal normalize HTTP field key
 */
final class Key
{
    private function __construct(public readonly string $value)
    {
    }

    /**
     * @throws SyntaxError If the string is not a valid HTTP value field key
     */
    public static function from(Stringable|string|int $httpValue): self
    {
        $key = (string) $httpValue;
        $instance = self::fromStringBeginning($key);
        if ($instance->value !== $key) {
            throw new SyntaxError('No valid http value key could be extracted from "'.$httpValue.'".');
        }

        return $instance;
    }

    public static function tryFrom(Stringable|string|int $httpValue): ?self
    {
        try {
            return self::from($httpValue);
        } catch (SyntaxError $e) {
            return null;
        }
    }

    /**
     * @throws SyntaxError If the string does not start with a valid HTTP value field key
     */
    public static function fromStringBeginning(string $httpValue): self
    {
        if (1 !== preg_match('/^(?<key>[a-z*][a-z\d.*_-]*)/', $httpValue, $found)) {
            throw new SyntaxError('No valid http value key could be extracted from "'.$httpValue.'".');
        }

        return new self($found['key']);
    }
}