using Stef.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
namespace WireMock.Matchers.Request;
///
/// The request cookie matcher.
///
///
public class RequestMessageCookieMatcher : IRequestMatcher
{
private readonly MatchBehaviour _matchBehaviour;
private readonly bool _ignoreCase;
///
/// The functions
///
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.
/// Ignore the case from the pattern.
/// The match behaviour.
public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, string name, string pattern, bool ignoreCase)
{
_matchBehaviour = matchBehaviour;
_ignoreCase = ignoreCase;
Name = Guard.NotNull(name);
Matchers = new IStringMatcher[] { new WildcardMatcher(matchBehaviour, Guard.NotNull(pattern), ignoreCase) };
}
///
/// Initializes a new instance of the class.
///
/// The match behaviour.
/// The name.
/// The patterns.
/// Ignore the case from the pattern.
public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, string name, bool ignoreCase, params string[] patterns) :
this(matchBehaviour, name, ignoreCase, patterns.Select(pattern => new WildcardMatcher(matchBehaviour, pattern, ignoreCase)).Cast().ToArray())
{
Guard.NotNull(patterns);
}
///
/// Initializes a new instance of the class.
///
/// The match behaviour.
/// The name.
/// The matchers.
/// Ignore the case from the pattern.
public RequestMessageCookieMatcher(MatchBehaviour matchBehaviour, string name, bool ignoreCase, params IStringMatcher[] matchers)
{
_matchBehaviour = matchBehaviour;
Name = Guard.NotNull(name);
Matchers = Guard.NotNull(matchers);
_ignoreCase = ignoreCase;
}
///
/// Initializes a new instance of the class.
///
/// The funcs.
public RequestMessageCookieMatcher(params Func, bool>[] funcs)
{
Guard.NotNull(funcs);
Funcs = funcs;
Name = string.Empty; // Not used when Func, but set to a non-null valid value.
}
///
public double GetMatchingScore(IRequestMessage requestMessage, IRequestMatchResult requestMatchResult)
{
double score = IsMatch(requestMessage);
return requestMatchResult.AddScore(GetType(), score);
}
private double IsMatch(IRequestMessage requestMessage)
{
if (requestMessage.Cookies == null)
{
return MatchBehaviourHelper.Convert(_matchBehaviour, MatchScores.Mismatch);
}
// Check if we want to use IgnoreCase to compare the Cookie-Name and Cookie-Value
var cookies = !_ignoreCase ? requestMessage.Cookies : new Dictionary(requestMessage.Cookies, StringComparer.OrdinalIgnoreCase);
if (Funcs != null)
{
return MatchScores.ToScore(Funcs.Any(f => f(cookies)));
}
if (Matchers == null)
{
return MatchScores.Mismatch;
}
if (!cookies.ContainsKey(Name))
{
return MatchBehaviourHelper.Convert(_matchBehaviour, MatchScores.Mismatch);
}
string value = cookies[Name];
return Matchers.Max(m => m.IsMatch(value));
}
}