using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using WireMock.Util;
using WireMock.Validation;
namespace WireMock.Matchers.Request
{
///
/// The request header matcher.
///
///
public class RequestMessageHeaderMatcher : IRequestMatcher
{
///
/// 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 RequestMessageHeaderMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, [NotNull] string pattern, bool ignoreCase)
{
Check.NotNull(name, nameof(name));
Check.NotNull(pattern, nameof(pattern));
Name = name;
Matchers = new IStringMatcher[] { new WildcardMatcher(matchBehaviour, pattern, ignoreCase) };
}
///
/// Initializes a new instance of the class.
///
/// The name.
/// The patterns.
/// Ignore the case from the pattern.
/// The match behaviour.
public RequestMessageHeaderMatcher(MatchBehaviour matchBehaviour, [NotNull] string name, [NotNull] string[] patterns, bool ignoreCase)
{
Check.NotNull(name, nameof(name));
Check.NotNull(patterns, nameof(patterns));
Name = name;
Matchers = patterns.Select(pattern => new WildcardMatcher(matchBehaviour, pattern, ignoreCase)).Cast().ToArray();
}
///
/// Initializes a new instance of the class.
///
/// The name.
/// The matchers.
public RequestMessageHeaderMatcher([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 RequestMessageHeaderMatcher([NotNull] params Func, bool>[] funcs)
{
Check.NotNull(funcs, nameof(funcs));
Funcs = funcs;
}
///
public double GetMatchingScore(RequestMessage requestMessage, RequestMatchResult requestMatchResult)
{
double score = IsMatch(requestMessage);
return requestMatchResult.AddScore(GetType(), score);
}
private double IsMatch(RequestMessage requestMessage)
{
if (requestMessage.Headers == null)
{
return MatchScores.Mismatch;
}
if (Funcs != null)
{
return MatchScores.ToScore(Funcs.Any(f => f(requestMessage.Headers.ToDictionary(entry => entry.Key, entry => entry.Value.ToArray()))));
}
if (Matchers == null)
{
return MatchScores.Mismatch;
}
if (!requestMessage.Headers.ContainsKey(Name))
{
return MatchScores.Mismatch;
}
WireMockList list = requestMessage.Headers[Name];
return Matchers.Max(m => list.Max(value => m.IsMatch(value))); // TODO : is this correct ?
}
}
}