using AnyOfTypes; using DevLab.JmesPath; using JetBrains.Annotations; using Newtonsoft.Json; using System.Linq; using WireMock.Extensions; using WireMock.Models; using Stef.Validation; namespace WireMock.Matchers { /// /// http://jmespath.org/ /// public class JmesPathMatcher : IStringMatcher, IObjectMatcher { private readonly AnyOf[] _patterns; /// public MatchBehaviour MatchBehaviour { get; } /// public bool ThrowException { get; } /// /// Initializes a new instance of the class. /// /// The patterns. public JmesPathMatcher([NotNull] params string[] patterns) : this(MatchBehaviour.AcceptOnMatch, false, patterns.ToAnyOfPatterns()) { } /// /// Initializes a new instance of the class. /// /// The patterns. public JmesPathMatcher([NotNull] params AnyOf[] patterns) : this(MatchBehaviour.AcceptOnMatch, false, patterns) { } /// /// Initializes a new instance of the class. /// /// Throw an exception when the internal matching fails because of invalid input. /// The patterns. public JmesPathMatcher(bool throwException = false, [NotNull] params AnyOf[] patterns) : this(MatchBehaviour.AcceptOnMatch, throwException, patterns) { } /// /// Initializes a new instance of the class. /// /// The match behaviour. /// Throw an exception when the internal matching fails because of invalid input. /// The patterns. public JmesPathMatcher(MatchBehaviour matchBehaviour, bool throwException = false, [NotNull] params AnyOf[] patterns) { Guard.NotNull(patterns, nameof(patterns)); MatchBehaviour = matchBehaviour; ThrowException = throwException; _patterns = patterns; } /// public double IsMatch(string input) { double match = MatchScores.Mismatch; if (input != null) { try { match = MatchScores.ToScore(_patterns.Select(pattern => bool.Parse(new JmesPath().Transform(input, pattern.GetPattern())))); } catch (JsonException) { if (ThrowException) { throw; } } } return MatchBehaviourHelper.Convert(MatchBehaviour, match); } /// public double IsMatch(object input) { double match = MatchScores.Mismatch; // When input is null or byte[], return Mismatch. if (input != null && !(input is byte[])) { string inputAsString = JsonConvert.SerializeObject(input); return IsMatch(inputAsString); } return MatchBehaviourHelper.Convert(MatchBehaviour, match); } /// public AnyOf[] GetPatterns() { return _patterns; } /// public string Name => "JmesPathMatcher"; } }