Repository navigation
Expand file tree
/
Copy pathBinaryCodec.php
More file actions
103 lines (89 loc) · 2.9 KB
/
Copy pathBinaryCodec.php
File metadata and controls
103 lines (89 loc) · 2.9 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
namespace Illuminate\Support;
use InvalidArgumentException;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
use Symfony\Component\Uid\Ulid;
class BinaryCodec
{
/** @var array<string, array{encode: callable(UuidInterface|Ulid|string|null): ?string, decode: callable(?string): ?string}> */
protected static array $customCodecs = [];
/**
* Register a custom codec.
*/
public static function register(string $name, callable $encode, callable $decode): void
{
self::$customCodecs[$name] = [
'encode' => $encode,
'decode' => $decode,
];
}
/**
* Encode a value to binary.
*
* @throws \InvalidArgumentException
*/
public static function encode(UuidInterface|Ulid|string|null $value, string $format): ?string
{
if (blank($value)) {
return null;
}
if (isset(self::$customCodecs[$format])) {
return (self::$customCodecs[$format]['encode'])($value);
}
return match ($format) {
'uuid' => match (true) {
$value instanceof UuidInterface => $value->getBytes(),
self::isBinary($value) => $value,
default => Uuid::fromString($value)->getBytes(),
},
'ulid' => match (true) {
$value instanceof Ulid => $value->toBinary(),
self::isBinary($value) => $value,
default => Ulid::fromString($value)->toBinary(),
},
default => throw new InvalidArgumentException("Format [$format] is invalid."),
};
}
/**
* Decode a binary value to string.
*
* @throws \InvalidArgumentException
*/
public static function decode(?string $value, string $format): ?string
{
if (blank($value)) {
return null;
}
if (isset(self::$customCodecs[$format])) {
return (self::$customCodecs[$format]['decode'])($value);
}
return match ($format) {
'uuid' => (self::isBinary($value) ? Uuid::fromBytes($value) : Uuid::fromString($value))->toString(),
'ulid' => (self::isBinary($value) ? Ulid::fromBinary($value) : Ulid::fromString($value))->toString(),
default => throw new InvalidArgumentException("Format [$format] is invalid."),
};
}
/**
* Get all available format names.
*
* @return array<string>
*/
public static function formats(): array
{
return array_unique([...['uuid', 'ulid'], ...array_keys(self::$customCodecs)]);
}
/**
* Determine if the given value is binary data.
*/
public static function isBinary(mixed $value): bool
{
if (! is_string($value) || $value === '') {
return false;
}
if (str_contains($value, "\0")) {
return true;
}
return ! mb_check_encoding($value, 'UTF-8');
}
}