diff --git a/README.md b/README.md index c86640c6..bbdfa2c2 100644 --- a/README.md +++ b/README.md @@ -905,8 +905,12 @@ to_json(""[, pretty: ""][, error_string: ""]) Replaces the value with its Base64 encoding. +Options: + +-`url_safe`: Perform URL-safe encoding (uses Base64URL format). (Default: `false`) + ```perl -to_base64("") +to_base64(""[, url_safe: ""]) ``` [Example in Playground](https://metafacture.org/playground/?example=to_base64) diff --git a/metafix/src/main/java/org/metafacture/metafix/FixMethod.java b/metafix/src/main/java/org/metafacture/metafix/FixMethod.java index 644e9cc3..273b4d41 100644 --- a/metafix/src/main/java/org/metafacture/metafix/FixMethod.java +++ b/metafix/src/main/java/org/metafacture/metafix/FixMethod.java @@ -680,7 +680,10 @@ public void apply(final Metafix metafix, final Record record, final List to_base64 { @Override public void apply(final Metafix metafix, final Record record, final List params, final Map options) { - record.transform(params.get(0), s -> Base64.getEncoder().encodeToString(s.getBytes())); + final boolean urlSafe = getBoolean(options, "url_safe"); + final Base64.Encoder encoder = urlSafe ? Base64.getUrlEncoder() : Base64.getEncoder(); + + record.transform(params.get(0), s -> encoder.encodeToString(s.getBytes())); } }, to_json { diff --git a/metafix/src/test/java/org/metafacture/metafix/MetafixMethodTest.java b/metafix/src/test/java/org/metafacture/metafix/MetafixMethodTest.java index 8b167257..d5886ebd 100644 --- a/metafix/src/test/java/org/metafacture/metafix/MetafixMethodTest.java +++ b/metafix/src/test/java/org/metafacture/metafix/MetafixMethodTest.java @@ -36,6 +36,8 @@ @ExtendWith(MetafixToDo.Extension.class) public class MetafixMethodTest { + private static final String YOUTUBE_URL = "https://www.youtube.com/watch?v=daLgsPSvD9A"; + @Mock private StreamReceiver streamReceiver; @@ -4084,6 +4086,37 @@ public void shouldTransformStringToBase64() { ); } + @Test + public void shouldTransformUrlSafeToBase64() { + urlToBase64(",url_safe:'true'", "aHR0cHM6Ly93d3cueW91dHViZS5jb20vd2F0Y2g_dj1kYUxnc1BTdkQ5QQ=="); + } + + @Test + public void shouldTransformNotUrlSafeToBase64AsDefault() { + urlToBase64("", "aHR0cHM6Ly93d3cueW91dHViZS5jb20vd2F0Y2g/dj1kYUxnc1BTdkQ5QQ=="); + } + + private void urlToBase64(final String option, final String expected) { + MetafixTestHelpers.assertFix(streamReceiver, Arrays.asList( + "to_base64('data.title'" + option + ")" + ), + i -> { + i.startRecord("1"); + i.startEntity("data"); + i.literal("title", YOUTUBE_URL); + i.endEntity(); + i.endRecord(); + }, + o -> { + o.get().startRecord("1"); + o.get().startEntity("data"); + o.get().literal("title", expected); + o.get().endEntity(); + o.get().endRecord(); + } + ); + } + @Test // checkstyle-disable-line JavaNCSS public void shouldCreateVariableFromLiteralValue() { MetafixTestHelpers.assertFix(streamReceiver, Arrays.asList(