Page MenuHomeDevCentral

D2276.diff
No OneTemporary

D2276.diff

diff --git a/src/Strings/Multibyte/StringUtilities.php b/src/Strings/Multibyte/StringUtilities.php
--- a/src/Strings/Multibyte/StringUtilities.php
+++ b/src/Strings/Multibyte/StringUtilities.php
@@ -57,4 +57,32 @@
return strpos($string, $needle) !== false;
}
+ /**
+ * Encode a string using a variant of the MIME base64 compatible with URLs.
+ *
+ * The + and / characters used in base64 are replaced by - and _.
+ * The = padding is removed.
+ *
+ * @param string $string The string to encode
+ * @return string The encoded string
+ */
+ public static function encodeInBase64 (string $string) : string {
+ return str_replace(
+ ['+', '/', '='],
+ ['-', '_', ''],
+ base64_encode($string)
+ );
+ }
+
+ /**
+ * Decode a string encoded with StringUtilities::encodeInBase64
+ *
+ * @param string $string The string to decode
+ * @return string The decoded string
+ */
+ public static function decodeFromBase64 (string $string) : string {
+ $toDecode = str_replace(['-', '_'], ['+', '/'], $string);
+ return base64_decode($toDecode);
+ }
+
}
diff --git a/tests/Strings/Multibyte/StringUtilitiesTest.php b/tests/Strings/Multibyte/StringUtilitiesTest.php
--- a/tests/Strings/Multibyte/StringUtilitiesTest.php
+++ b/tests/Strings/Multibyte/StringUtilitiesTest.php
@@ -54,6 +54,22 @@
$this->assertFalse(StringUtilities::endsWith("foo", "bar"));
}
+ /**
+ * @dataProvider provideBase64
+ */
+ public function testEncodeInBase64 (string $decoded, string $encoded) : void {
+ $actual = StringUtilities::encodeInBase64($decoded);
+ $this->assertEquals($encoded, $actual);
+ }
+
+ /**
+ * @dataProvider provideBase64
+ */
+ public function testDecodeFromBase64 (string $decoded, string $encoded) : void {
+ $actual = StringUtilities::decodeFromBase64($encoded);
+ $this->assertEquals($decoded, $actual);
+ }
+
///
/// Data providers
///
@@ -89,4 +105,18 @@
yield ['FOOBAR', "FOOBAR", 0, "àèò", STR_PAD_RIGHT];
yield ['FOOBAR', "FOOBAR", -10, "àèò", STR_PAD_RIGHT];
}
+
+ public function provideBase64 () : iterable {
+ yield ['foo', 'Zm9v', "This is the regular base test without any exception."];
+ yield ['', '', "An empty string should remain an empty string."];
+ yield [
+ "J'ai fait mes 60 prières par terre dans la poudrière.",
+ 'SidhaSBmYWl0IG1lcyA2MCBwcmnDqHJlcyBwYXIgdGVycmUgZGFucyBsYSBwb3VkcmnDqHJlLg',
+ "No padding should be used."
+ ];
+ yield [
+ "àèòàFOOàèòà", "w6DDqMOyw6BGT0_DoMOow7LDoA",
+ "Slashes / should be replaced by underscores _."
+ ];
+ }
}

File Metadata

Mime Type
text/plain
Expires
Sun, Apr 20, 11:26 (19 h, 48 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2582225
Default Alt Text
D2276.diff (2 KB)

Event Timeline