35 lines
924 B
PHP
35 lines
924 B
PHP
|
<?php
|
||
|
// UriBase64Serialiser.php
|
||
|
// Created: 2022-01-13
|
||
|
// Updated: 2022-02-27
|
||
|
|
||
|
namespace Index\Serialisation;
|
||
|
|
||
|
use Index\IO\Stream;
|
||
|
|
||
|
/**
|
||
|
* Provides URL-safe Base64 encoding.
|
||
|
*/
|
||
|
class UriBase64Serialiser extends Serialiser {
|
||
|
/**
|
||
|
* Encodes binary data as a Base64 string.
|
||
|
*
|
||
|
* @param string $input Input binary data.
|
||
|
* @return string Base64 string representing the binary data.
|
||
|
*/
|
||
|
public function serialise(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 function deserialise(Stream|string $input): mixed {
|
||
|
$input = (string)$input;
|
||
|
return base64_decode(str_pad(strtr($input, '-_', '+/'), strlen($input) % 4, '=', STR_PAD_RIGHT));
|
||
|
}
|
||
|
}
|