using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using WireMock.Validation;
namespace WireMock.Matchers.Request
{
///
/// The request cookie matcher.
///
public class RequestMessageCookieMatcher : IRequestMatcher
{
///
/// The funcs.
///
public Func, bool>[] Funcs { get; }
///
/// The name
///
public string Name { get; }
///
/// The matchers.
///
public IStringMatcher[] Matchers { get; }
///
/// Initializes a new instance of the class.
///
/// The name.
/// The pattern.
/// The ignoreCase.
public RequestMessageCookieMatcher([NotNull] string name, [NotNull] string pattern, bool ignoreCase = true)
{
Check.NotNull(name, nameof(name));
Check.NotNull(pattern, nameof(pattern));
Name = name;
Matchers = new IStringMatcher[] { new WildcardMatcher(pattern, ignoreCase) };
}
///
/// Initializes a new instance of the class.
///
/// The name.
/// The matchers.
public RequestMessageCookieMatcher([NotNull] string name, [NotNull] params IStringMatcher[] matchers)
{
Check.NotNull(name, nameof(name));
Check.NotNull(matchers, nameof(matchers));
Name = name;
Matchers = matchers;
}
///
/// Initializes a new instance of the class.
///
/// The funcs.
public RequestMessageCookieMatcher([NotNull] params Func, bool>[] funcs)
{
Check.NotNull(funcs, nameof(funcs));
Funcs = funcs;
}
///
/// Determines whether the specified RequestMessage is match.
///
/// The RequestMessage.
/// The RequestMatchResult.
///
/// A value between 0.0 - 1.0 of the similarity.
///
public double GetMatchingScore(RequestMessage requestMessage, RequestMatchResult requestMatchResult)
{
double score = IsMatch(requestMessage);
return requestMatchResult.AddScore(GetType(), score);
}
private double IsMatch(RequestMessage requestMessage)
{
if (requestMessage.Cookies == null)
{
return MatchScores.Mismatch;
}
if (Funcs != null)
{
return MatchScores.ToScore(Funcs.Any(f => f(requestMessage.Cookies)));
}
if (Matchers == null)
{
return MatchScores.Mismatch;
}
if (!requestMessage.Cookies.ContainsKey(Name))
{
return MatchScores.Mismatch;
}
string value = requestMessage.Cookies[Name];
return Matchers.Max(m => m.IsMatch(value));
}
}
}