| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Text; |
| | | 3 | | using System.Text.Json; |
| | | 4 | | using Elsa.Expressions.Liquid.Contracts; |
| | | 5 | | using Fluid; |
| | | 6 | | using Fluid.Values; |
| | | 7 | | |
| | | 8 | | namespace Elsa.Expressions.Liquid.Filters; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// A liquid filter that converts a value into a base 64 string representation. |
| | | 12 | | /// </summary> |
| | | 13 | | public class Base64Filter : ILiquidFilter |
| | | 14 | | { |
| | | 15 | | /// <inheritdoc /> |
| | | 16 | | public ValueTask<FluidValue> ProcessAsync(FluidValue input, FilterArguments arguments, TemplateContext context) |
| | | 17 | | { |
| | 0 | 18 | | var text = InputToString(input, context); |
| | | 19 | | |
| | 0 | 20 | | if (text == null) |
| | 0 | 21 | | return new ValueTask<FluidValue>(NilValue.Instance); |
| | | 22 | | |
| | 0 | 23 | | var bytes = Encoding.UTF8.GetBytes(text); |
| | 0 | 24 | | var base64 = Convert.ToBase64String(bytes); |
| | | 25 | | |
| | 0 | 26 | | return new ValueTask<FluidValue>(new StringValue(base64)); |
| | | 27 | | } |
| | | 28 | | |
| | | 29 | | private static string? InputToString(FluidValue input, TemplateContext context) |
| | | 30 | | { |
| | 0 | 31 | | return input.Type switch |
| | 0 | 32 | | { |
| | 0 | 33 | | FluidValues.Array => JsonSerializer.Serialize(input.Enumerate(context).Select(o => o.ToObjectValue())), |
| | 0 | 34 | | FluidValues.Boolean => input.ToBooleanValue().ToString(), |
| | 0 | 35 | | FluidValues.Nil => null, |
| | 0 | 36 | | FluidValues.Number => input.ToNumberValue().ToString(CultureInfo.InvariantCulture), |
| | 0 | 37 | | FluidValues.DateTime or FluidValues.Dictionary or FluidValues.Object => JsonSerializer.Serialize(input.ToObj |
| | 0 | 38 | | FluidValues.String => input.ToStringValue(), |
| | 0 | 39 | | _ => throw new ArgumentOutOfRangeException(nameof(input), "Unrecognized FluidValue") |
| | 0 | 40 | | }; |
| | | 41 | | } |
| | | 42 | | } |