aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/bakame/http-structured-fields/src/Bytes.php
blob: aa747b76bcafc4c9cd4552f8a0c72239a1b88db6 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php

declare(strict_types=1);

namespace Bakame\Http\StructuredFields;

use Stringable;
use Throwable;

use function base64_decode;
use function base64_encode;
use function preg_match;

/**
 * @see https://www.rfc-editor.org/rfc/rfc9651.html#section-3.3.5
 */
final class Bytes
{
    private function __construct(private readonly string $value)
    {
    }

    /**
     * Returns a new instance from a Base64 encoded string.
     */
    public static function fromEncoded(Stringable|string $encoded): self
    {
        $encoded = (string) $encoded;
        if (1 !== preg_match('/^[a-z\d+\/=]*$/i', $encoded)) {
            throw new SyntaxError('The byte sequence '.$encoded.' contains invalid characters.');
        }

        $decoded = base64_decode($encoded, true);
        if (false === $decoded) {
            throw new SyntaxError('Unable to base64 decode the byte sequence '.$encoded);
        }

        return new self($decoded);
    }

    public static function tryFromEncoded(Stringable|string $encoded): ?self
    {
        try {
            return self::fromEncoded($encoded);
        } catch (Throwable) {
            return null;
        }
    }

    /**
     * Returns a new instance from a raw decoded string.
     */
    public static function fromDecoded(Stringable|string $decoded): self
    {
        return new self((string) $decoded);
    }

    /**
     * Returns the decoded string.
     */
    public function decoded(): string
    {
        return $this->value;
    }

    /**
     * Returns the base64 encoded string.
     */
    public function encoded(): string
    {
        return base64_encode($this->value);
    }

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

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