aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/bakame/http-structured-fields/src/Token.php
blob: 88f41dbe8832033a3158da819d777a3fbead53d2 (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
<?php

declare(strict_types=1);

namespace Bakame\Http\StructuredFields;

use Stringable;
use Throwable;

use function preg_match;

/**
 * @see https://www.rfc-editor.org/rfc/rfc9651.html#name-tokens
 */
final class Token
{
    private function __construct(private readonly string $value)
    {
        if (1 !== preg_match("/^([a-z*][a-z\d:\/!#\$%&'*+\-.^_`|~]*)$/i", $this->value)) {
            throw new SyntaxError('The token '.$this->value.' contains invalid characters.');
        }
    }

    public function toString(): string
    {
        return $this->value;
    }

    public static function tryFromString(Stringable|string $value): ?self
    {
        try {
            return self::fromString($value);
        } catch (Throwable) {
            return null;
        }
    }

    public static function fromString(Stringable|string $value): self
    {
        return new self((string)$value);
    }

    public function equals(mixed $other): bool
    {
        return $other instanceof self && $other->value === $this->value;
    }

    public function type(): Type
    {
        return Type::Token;
    }
}