|
13 | 13 |
|
14 | 14 | use AssertionError; |
15 | 15 | use InvalidArgumentException; |
| 16 | +use function base64_decode; |
| 17 | +use function base64_encode; |
16 | 18 | use function chr; |
17 | 19 | use function ctype_digit; |
18 | 20 | use function ctype_xdigit; |
19 | 21 | use function dechex; |
20 | 22 | use function explode; |
21 | 23 | use function gethostbyname; |
22 | 24 | use function gettimeofday; |
| 25 | +use function hex2bin; |
23 | 26 | use function hexdec; |
24 | 27 | use function in_array; |
25 | 28 | use function md5; |
@@ -251,7 +254,46 @@ public static function v1(string|int $address = null): string |
251 | 254 | } |
252 | 255 |
|
253 | 256 | /** |
254 | | - * Creates the v3 and/or v5 UUID. |
| 257 | + * Creates a base64 string out of the UUID. |
| 258 | + * |
| 259 | + * @param string $uuid UUID string |
| 260 | + * |
| 261 | + * @return string base64 encoded string |
| 262 | + */ |
| 263 | + public static function toBase64(string $uuid): string |
| 264 | + { |
| 265 | + if (false === UUID::valid($uuid)) { |
| 266 | + throw new InvalidArgumentException('Invalid UUID ' . $uuid); |
| 267 | + } |
| 268 | + return str_replace(['/', '+', '='], ['-', '_', ''], |
| 269 | + base64_encode(hex2bin(str_replace('-', '', $uuid))) |
| 270 | + ); |
| 271 | + } |
| 272 | + |
| 273 | + /** |
| 274 | + * Converts a base64 string to UUID. |
| 275 | + * |
| 276 | + * @param string $base64 |
| 277 | + * |
| 278 | + * @return string UUID string |
| 279 | + */ |
| 280 | + public static function fromBase64(string $base64): string |
| 281 | + { |
| 282 | + $uuid = base64_decode(str_replace( |
| 283 | + ['-', '_', '='], ['/', '+', ''], $base64) . '==' |
| 284 | + ); |
| 285 | + if (!preg_match('//u', $uuid)) { |
| 286 | + $uuid = vsprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', unpack('n*', $uuid)); |
| 287 | + } |
| 288 | + if (UUID::valid($uuid)) { |
| 289 | + return $uuid; |
| 290 | + } |
| 291 | + throw new InvalidArgumentException( |
| 292 | + 'Failed to convert base 64 string to UUID'); |
| 293 | + } |
| 294 | + |
| 295 | + /** |
| 296 | + * Creates a v3 or v5 UUID. |
255 | 297 | * |
256 | 298 | * @param string $namespace UUID namespace identifier (see UUID constants) |
257 | 299 | * @param string $name A name |
|
0 commit comments