using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using WireMock.Util; using WireMock.Validation; namespace WireMock.Matchers.Request { /// /// The request parameters matcher. /// public class RequestMessageParamMatcher : IRequestMatcher { private readonly MatchBehaviour _matchBehaviour; /// /// The funcs /// public Func>, bool>[] Funcs { get; } /// /// The key /// public string Key { get; } /// /// The values /// public IEnumerable Values { get; } /// /// Initializes a new instance of the class. /// /// The match behaviour. /// The key. public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key) : this(matchBehaviour, key, null) { } /// /// Initializes a new instance of the class. /// /// The match behaviour. /// The key. /// The values. public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, [CanBeNull] IEnumerable values) { Check.NotNull(key, nameof(key)); _matchBehaviour = matchBehaviour; Key = key; Values = values; } /// /// Initializes a new instance of the class. /// /// The funcs. public RequestMessageParamMatcher([NotNull] params Func>, bool>[] funcs) { Check.NotNull(funcs, nameof(funcs)); Funcs = funcs; } /// public double GetMatchingScore(RequestMessage requestMessage, RequestMatchResult requestMatchResult) { double score = MatchBehaviourHelper.Convert(_matchBehaviour, IsMatch(requestMessage)); return requestMatchResult.AddScore(GetType(), score); } private double IsMatch(RequestMessage requestMessage) { if (Funcs != null) { return MatchScores.ToScore(requestMessage.Query != null && Funcs.Any(f => f(requestMessage.Query))); } var values = requestMessage.GetParameter(Key); if (values == null) { // Key is not present, just return Mismatch return MatchScores.Mismatch; } if (values.Count == 0 && (Values == null || !Values.Any())) { // Key is present, but no values or null, just return Perfect return MatchScores.Perfect; } var matches = Values.Select(v => values.Contains(v)); return MatchScores.ToScore(matches); } } }