Made syntax of URI-safe base64 methods compatible with the built in base64_* methods.

This commit is contained in:
flash 2024-07-31 18:20:29 +00:00
parent 27d28f03ce
commit 4b4ff9f7c4
2 changed files with 13 additions and 15 deletions

View file

@ -1 +1 @@
0.2407.311814
0.2407.311820

View file

@ -1,34 +1,32 @@
<?php
// UriBase64.php
// Created: 2022-01-13
// Updated: 2023-08-03
// Updated: 2024-07-31
namespace Index\Serialisation;
use Index\IO\Stream;
/**
* Provides URL-safe Base64 encoding.
*/
final class UriBase64 {
/**
* Encodes binary data as a Base64 string.
* Encodes data with URI-safe MIME base64.
*
* @param string $input Input binary data.
* @return string Base64 string representing the binary data.
* @param string $string The data to encode.
* @return string The encoded data, as a string.
*/
public static function encode(mixed $input): string {
return rtrim(strtr(base64_encode((string)$input), '+/', '-_'), '=');
public static function encode(string $string): string {
return rtrim(strtr(base64_encode($string), '+/', '-_'), '=');
}
/**
* Decodes a Base64 string back to binary data.
* Decodes data encoded with URI-safe MIME base64.
*
* @param Stream|string $input Input Base64 string.
* @return string|false Binary data.
* @param string $string The encoded data.
* @param bool $strict If the strict parameter is set to true then the base64_decode() function will return false if the input contains character from outside the base64 alphabet. Otherwise invalid characters will be silently discarded.
* @return string|false Returns the decoded data or false on failure. The returned data may be binary.
*/
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));
public static function decode(string $string, bool $strict = false): string|false {
return base64_decode(str_pad(strtr($string, '-_', '+/'), strlen($string) % 4, '=', STR_PAD_RIGHT));
}
}