Skip to content

Commit

Permalink
Add support for conversion to form url encoded string
Browse files Browse the repository at this point in the history
  • Loading branch information
nikoraes committed Oct 31, 2024
1 parent 975f51c commit 26bff98
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
24 changes: 24 additions & 0 deletions JexlNet.ExtendedGrammar/ExtendedGrammar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,10 @@ public ExtendedGrammar()
AddFunction("base64Decode", Base64Decode);
AddFunction("$base64Decode", Base64Decode);
AddTransform("base64Decode", Base64Decode);
// URLFormEncoded
AddFunction("formUrlEncoded", FormUrlEncoded);
AddFunction("$formUrlEncoded", FormUrlEncoded);
AddTransform("formUrlEncoded", FormUrlEncoded);
// Regex
AddFunction("regexMatch", RegexMatch);
AddFunction("$regexMatch", RegexMatch);
Expand Down Expand Up @@ -707,6 +711,26 @@ public static JsonNode Base64Decode(JsonNode input)
return null;
}

/// <summary>
/// Converts an object to a form URL encoded string.
/// </summary>
/// <param name="input"></param>
/// <example><code>formUrlEncoded(obj)</code><code>$formUrlEncoded(obj)</code><code>obj|formUrlEncoded</code></example>
/// <returns>A form url encoded string</returns>
public static JsonNode FormUrlEncoded(JsonNode input)
{
if (input is JsonValue value)
{
string str = value.ToString();
return Uri.EscapeDataString(str);
}
else if (input is JsonObject obj)
{
return string.Join("&", obj.Select(x => $"{Uri.EscapeDataString(x.Key)}={Uri.EscapeDataString(x.Value.ToString())}"));
}
return null;
}

/// <summary>
/// Check whether a string matches a regex pattern
/// </summary>
Expand Down
10 changes: 9 additions & 1 deletion JexlNet.Test/ExtendedGrammar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,14 @@ public void ConvertBase64(string expression, string expected)
Assert.Equal(expected, result?.ToString());
}

[Theory]
[InlineData("{foo:'bar',baz:'tek'}|formUrlEncoded", "foo=bar&baz=tek")]
public void ConvertFormUrlEncoded(string expression, string expected)
{
var jexl = new Jexl(new ExtendedGrammar());
var result = jexl.Eval(expression);
Assert.Equal(expected, result?.ToString());
}

[Theory]
[InlineData("'foobar'|regexMatch('foo')", true)]
Expand Down Expand Up @@ -261,7 +269,7 @@ public void Boolean(string expression, bool? expected)
[Theory]
[InlineData("2|case(1,'a',2,'b',3,'c')", "b")]
[InlineData("$case('bar','foo','a','bar','b','baz','c')", "b")]
[InlineData("'notfound'|case('bar','foo','a','bar','b','baz','c','b')", "b")]
[InlineData("'notfound'|case('bar','foo','a','bar','b','baz','c','b','b')", "b")]
public void Case(string expression, string expected)
{
var jexl = new Jexl(new ExtendedGrammar());
Expand Down

0 comments on commit 26bff98

Please sign in to comment.