| | | 1 | | using System; |
| | | 2 | | using System.Linq; |
| | | 3 | | using System.Text.RegularExpressions; |
| | | 4 | | using HandlebarsDotNet; |
| | | 5 | | using WireMock.Util; |
| | | 6 | | using WireMock.Validation; |
| | | 7 | | |
| | | 8 | | namespace WireMock.Transformers |
| | | 9 | | { |
| | | 10 | | internal static class HandleBarsRegex |
| | | 11 | | { |
| | | 12 | | public static void Register() |
| | 1 | 13 | | { |
| | 1 | 14 | | Handlebars.RegisterHelper("Regex.Match", (writer, context, arguments) => |
| | 4 | 15 | | { |
| | 4 | 16 | | (string stringToProcess, string regexPattern, object defaultValue) = ParseArguments(arguments); |
| | 1 | 17 | | |
| | 4 | 18 | | Match match = Regex.Match(stringToProcess, regexPattern); |
| | 1 | 19 | | |
| | 4 | 20 | | if (match.Success) |
| | 2 | 21 | | { |
| | 2 | 22 | | writer.WriteSafeString(match.Value); |
| | 2 | 23 | | } |
| | 3 | 24 | | else if (defaultValue != null) |
| | 2 | 25 | | { |
| | 2 | 26 | | writer.WriteSafeString(defaultValue); |
| | 2 | 27 | | } |
| | 4 | 28 | | }); |
| | | 29 | | |
| | 1 | 30 | | Handlebars.RegisterHelper("Regex.Match", (writer, options, context, arguments) => |
| | 5 | 31 | | { |
| | 5 | 32 | | (string stringToProcess, string regexPattern, object defaultValue) = ParseArguments(arguments); |
| | 1 | 33 | | |
| | 4 | 34 | | var regex = new Regex(regexPattern); |
| | 4 | 35 | | var namedGroups = RegexUtils.GetNamedGroups(regex, stringToProcess); |
| | 4 | 36 | | if (namedGroups.Any()) |
| | 2 | 37 | | { |
| | 2 | 38 | | options.Template(writer, namedGroups); |
| | 2 | 39 | | } |
| | 3 | 40 | | else if (defaultValue != null) |
| | 2 | 41 | | { |
| | 2 | 42 | | options.Template(writer, defaultValue); |
| | 2 | 43 | | } |
| | 4 | 44 | | }); |
| | 1 | 45 | | } |
| | | 46 | | |
| | | 47 | | private static (string stringToProcess, string regexPattern, object defaultValue) ParseArguments(object[] argume |
| | 7 | 48 | | { |
| | 14 | 49 | | Check.Condition(arguments, args => args.Length == 2 || args.Length == 3, nameof(arguments)); |
| | | 50 | | |
| | | 51 | | string ParseAsString(object arg) |
| | 13 | 52 | | { |
| | 13 | 53 | | if (arg is string) |
| | 12 | 54 | | { |
| | 12 | 55 | | return (string) arg; |
| | | 56 | | } |
| | | 57 | | else |
| | 1 | 58 | | { |
| | 1 | 59 | | throw new NotSupportedException($"The value '{arg}' with type '{arg?.GetType()}' cannot be used in H |
| | | 60 | | } |
| | 12 | 61 | | } |
| | | 62 | | |
| | 7 | 63 | | return (ParseAsString(arguments[0]), ParseAsString(arguments[1]), arguments.Length == 3 ? arguments[2] : nul |
| | 6 | 64 | | } |
| | | 65 | | } |
| | | 66 | | } |