index/src/Serialisation/UriBase64.php

33 lines
1.1 KiB
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
// Updated: 2024-07-31
2022-09-13 13:13:11 +00:00
namespace Index\Serialisation;
/**
* 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 data with URI-safe MIME base64.
2022-09-13 13:13:11 +00:00
*
* @param string $string The data to encode.
* @return string The encoded data, as a string.
2022-09-13 13:13:11 +00:00
*/
public static function encode(string $string): string {
return rtrim(strtr(base64_encode($string), '+/', '-_'), '=');
2022-09-13 13:13:11 +00:00
}
/**
* Decodes data encoded with URI-safe MIME base64.
2022-09-13 13:13:11 +00:00
*
* @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.
2022-09-13 13:13:11 +00:00
*/
public static function decode(string $string, bool $strict = false): string|false {
return base64_decode(str_pad(strtr($string, '-_', '+/'), strlen($string) % 4, '=', STR_PAD_RIGHT));
2022-09-13 13:13:11 +00:00
}
}