// Copyright © WireMock.Net
using System.Linq;
using Stef.Validation;
using WireMock.Util;
namespace WireMock.Matchers.Request;
///
/// The request body MultiPart matcher.
///
public class RequestMessageMultiPartMatcher : IRequestMatcher
{
///
/// The name of this matcher.
///
public const string Name = "MultiPartMatcher";
private readonly IMimeKitUtils _mimeKitUtils = LoadMimeKitUtils();
///
/// The matchers.
///
public IMatcher[]? Matchers { get; }
///
/// The
///
public MatchOperator MatchOperator { get; } = MatchOperator.And;
///
/// The
///
public MatchBehaviour MatchBehaviour { get; }
///
/// Initializes a new instance of the class.
///
/// The matchers.
public RequestMessageMultiPartMatcher(params IMatcher[] matchers)
{
Matchers = Guard.NotNull(matchers);
}
///
/// Initializes a new instance of the class.
///
/// The match behaviour.
/// The to use.
/// The matchers.
public RequestMessageMultiPartMatcher(MatchBehaviour matchBehaviour, MatchOperator matchOperator, params IMatcher[] matchers)
{
Matchers = Guard.NotNull(matchers);
MatchBehaviour = matchBehaviour;
MatchOperator = matchOperator;
}
///
public double GetMatchingScore(IRequestMessage requestMessage, IRequestMatchResult requestMatchResult)
{
var matchDetail = MatchResult.From(Name).ToMatchDetail();
Exception? exception = null;
if (Matchers == null)
{
return requestMatchResult.AddMatchDetail(matchDetail);
}
if (!_mimeKitUtils.TryGetMimeMessage(requestMessage, out var message))
{
return requestMatchResult.AddMatchDetail(matchDetail);
}
double score = MatchScores.Mismatch;
try
{
foreach (var mimePartMatcher in Matchers.OfType().ToArray())
{
score = MatchScores.Mismatch;
foreach (var mimeBodyPart in message.BodyParts)
{
var matchResult = mimePartMatcher.IsMatch(mimeBodyPart);
if (matchResult.IsPerfect())
{
score = MatchScores.Perfect;
break;
}
}
if ((MatchOperator == MatchOperator.Or && MatchScores.IsPerfect(score)) || (MatchOperator == MatchOperator.And && !MatchScores.IsPerfect(score)))
{
break;
}
}
}
catch (Exception ex)
{
exception = ex;
}
return requestMatchResult.AddMatchDetail(MatchResult.From(Name, score, exception).ToMatchDetail());
}
private static IMimeKitUtils LoadMimeKitUtils()
{
if (TypeLoader.TryLoadStaticInstance(out var mimeKitUtils))
{
return mimeKitUtils;
}
throw new InvalidOperationException("MimeKit is required for RequestMessageMultiPartMatcher. Please install the WireMock.Net.MimePart package.");
}
}