using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using WireMock.Validation;
namespace WireMock.Matchers.Request
{
///
/// The request ClientIP matcher.
///
public class RequestMessageClientIPMatcher : IRequestMatcher
{
///
/// The matchers.
///
public IReadOnlyList Matchers { get; }
///
/// The ClientIP functions.
///
public Func[] Funcs { get; }
///
/// Initializes a new instance of the class.
///
/// The clientIPs.
public RequestMessageClientIPMatcher([NotNull] params string[] clientIPs) : this(clientIPs.Select(ip => new WildcardMatcher(ip)).ToArray())
{
}
///
/// Initializes a new instance of the class.
///
/// The matchers.
public RequestMessageClientIPMatcher([NotNull] params IMatcher[] matchers)
{
Check.NotNull(matchers, nameof(matchers));
Matchers = matchers;
}
///
/// Initializes a new instance of the class.
///
/// The clientIP functions.
public RequestMessageClientIPMatcher([NotNull] params Func[] 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 (Matchers != null)
return Matchers.Max(matcher => matcher.IsMatch(requestMessage.ClientIP));
if (Funcs != null)
return MatchScores.ToScore(requestMessage.ClientIP != null && Funcs.Any(func => func(requestMessage.ClientIP)));
return MatchScores.Mismatch;
}
}
}