// Copyright © WireMock.Net
using System;
using System.Linq;
using Stef.Validation;
using WireMock.Util;
namespace WireMock.Matchers.Request;
///
/// The request body MultiPart matcher.
///
public class RequestMessageMultiPartMatcher : IRequestMatcher
{
private static readonly IMimeKitUtils MimeKitUtils = TypeLoader.LoadStaticInstance();
///
/// The matchers.
///
public IMatcher[]? Matchers { get; }
///
/// The
///
public MatchOperator MatchOperator { get; } = MatchOperator.Or;
///
/// 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 score = MatchScores.Mismatch;
Exception? exception = null;
if (Matchers?.Any() != true)
{
return requestMatchResult.AddScore(GetType(), score, null);
}
if (!MimeKitUtils.TryGetMimeMessage(requestMessage, out var message))
{
return requestMatchResult.AddScore(GetType(), score, null);
}
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.AddScore(GetType(), score, exception);
}
}