using DevLab.JmesPath; using JetBrains.Annotations; using Newtonsoft.Json; using System.Linq; using WireMock.Validation; namespace WireMock.Matchers { /// /// http://jmespath.org/ /// public class JmesPathMatcher : IStringMatcher, IObjectMatcher { private readonly string[] _patterns; /// public MatchBehaviour MatchBehaviour { get; } /// /// Initializes a new instance of the class. /// /// The patterns. public JmesPathMatcher([NotNull] params string[] patterns) : this(MatchBehaviour.AcceptOnMatch, patterns) { } /// /// Initializes a new instance of the class. /// /// The match behaviour. /// The patterns. public JmesPathMatcher(MatchBehaviour matchBehaviour, [NotNull] params string[] patterns) { Check.NotNull(patterns, nameof(patterns)); MatchBehaviour = matchBehaviour; _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)))); } catch (JsonException) { // just ignore JsonException } } 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 string[] GetPatterns() { return _patterns; } /// public string Name => "JmesPathMatcher"; } }