index/src/Serialisation/UriBase64.php

35 lines
897 B
PHP
Raw Normal View History

2022-09-13 13:13:11 +00:00
<?php
2023-07-21 21:47:41 +00:00
// UriBase64.php
2022-09-13 13:13:11 +00:00
// Created: 2022-01-13
2023-07-21 21:47:41 +00:00
// Updated: 2023-07-21
2022-09-13 13:13:11 +00:00
namespace Index\Serialisation;
use Index\IO\Stream;
/**
* Provides URL-safe Base64 encoding.
*/
2023-07-21 21:47:41 +00:00
final class UriBase64 {
2022-09-13 13:13:11 +00:00
/**
* Encodes binary data as a Base64 string.
*
* @param string $input Input binary data.
* @return string Base64 string representing the binary data.
*/
2023-07-21 21:47:41 +00:00
public static function encode(mixed $input): string {
2022-09-13 13:13:11 +00:00
return rtrim(strtr(base64_encode((string)$input), '+/', '-_'), '=');
}
/**
* Decodes a Base64 string back to binary data.
*
* @param Stream|string $input Input Base64 string.
* @return string Binary data.
*/
2023-07-21 21:47:41 +00:00
public static function decode(Stream|string $input): mixed {
2022-09-13 13:13:11 +00:00
$input = (string)$input;
return base64_decode(str_pad(strtr($input, '-_', '+/'), strlen($input) % 4, '=', STR_PAD_RIGHT));
}
}