index/src/Serialisation/UriBase64.php

34 lines
897 B
PHP

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