| 1 |
<?php |
| 2 |
|
| 3 |
namespace Illuminate\Support; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
use Ramsey\Uuid\Uuid; |
| 7 |
use Ramsey\Uuid\UuidInterface; |
| 8 |
use Symfony\Component\Uid\Ulid; |
| 9 |
|
| 10 |
class BinaryCodec |
| 11 |
{ |
| 12 |
|
| 13 |
protected static array $customCodecs = []; |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
public static function register(string $name, callable $encode, callable $decode): void |
| 19 |
{ |
| 20 |
self::$customCodecs[$name] = [ |
| 21 |
'encode' => $encode, |
| 22 |
'decode' => $decode, |
| 23 |
]; |
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
public static function encode(UuidInterface|Ulid|string|null $value, string $format): ?string |
| 30 |
{ |
| 31 |
if (blank($value)) { |
| 32 |
return null; |
| 33 |
} |
| 34 |
|
| 35 |
if (isset(self::$customCodecs[$format])) { |
| 36 |
return (self::$customCodecs[$format]['encode'])($value); |
| 37 |
} |
| 38 |
|
| 39 |
return match ($format) { |
| 40 |
'uuid' => match (true) { |
| 41 |
$value instanceof UuidInterface => $value->getBytes(), |
| 42 |
self::isBinary($value) => $value, |
| 43 |
default => Uuid::fromString($value)->getBytes(), |
| 44 |
}, |
| 45 |
'ulid' => match (true) { |
| 46 |
$value instanceof Ulid => $value->toBinary(), |
| 47 |
self::isBinary($value) => $value, |
| 48 |
default => Ulid::fromString($value)->toBinary(), |
| 49 |
}, |
| 50 |
default => throw new InvalidArgumentException("Format [$format] is invalid."), |
| 51 |
}; |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
public static function decode(?string $value, string $format): ?string |
| 58 |
{ |
| 59 |
if (blank($value)) { |
| 60 |
return null; |
| 61 |
} |
| 62 |
|
| 63 |
if (isset(self::$customCodecs[$format])) { |
| 64 |
return (self::$customCodecs[$format]['decode'])($value); |
| 65 |
} |
| 66 |
|
| 67 |
return match ($format) { |
| 68 |
'uuid' => (self::isBinary($value) ? Uuid::fromBytes($value) : Uuid::fromString($value))->toString(), |
| 69 |
'ulid' => (self::isBinary($value) ? Ulid::fromBinary($value) : Ulid::fromString($value))->toString(), |
| 70 |
default => throw new InvalidArgumentException("Format [$format] is invalid."), |
| 71 |
}; |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
public static function formats(): array |
| 80 |
{ |
| 81 |
return array_unique([...['uuid', 'ulid'], ...array_keys(self::$customCodecs)]); |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
public static function isBinary(mixed $value): bool |
| 88 |
{ |
| 89 |
if (! is_string($value) || $value === '') { |
| 90 |
return false; |
| 91 |
} |
| 92 |
|
| 93 |
if (str_contains($value, "\0")) { |
| 94 |
return true; |
| 95 |
} |
| 96 |
|
| 97 |
return ! mb_check_encoding($value, 'UTF-8'); |
| 98 |
} |
| 99 |
} |