index/src/Serialisation/UriBase64.php

35 lines
909 B
PHP

<?php
// UriBase64.php
// Created: 2022-01-13
// Updated: 2023-08-03
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|false Binary data.
*/
public static function decode(Stream|string $input): string|bool {
$input = (string)$input;
return base64_decode(str_pad(strtr($input, '-_', '+/'), strlen($input) % 4, '=', STR_PAD_RIGHT));
}
}