using System;
using System.Collections.Generic;
using System.Linq;
using Stef.Validation;
using WireMock.Util;
namespace WireMock.Matchers.Request;
///
/// The request body MultiPart matcher.
///
public class RequestMessageMultiPartMatcher : IRequestMatcher
{
///
/// 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)
{
#if !MIMEKIT
throw new System.NotSupportedException("The MultiPartMatcher can not be used for .NETStandard1.3 or .NET Framework 4.6.1 or lower.");
#else
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
{
var mimePartMatchers = Matchers.OfType().ToArray();
foreach (var mimePart in message.BodyParts.OfType())
{
var matchesForMimePart = new List { default };
matchesForMimePart.AddRange(mimePartMatchers.Select(matcher => matcher.IsMatch(mimePart)));
score = matchesForMimePart.Select(m => m.Score).Max();
if (MatchScores.IsPerfect(score))
{
if (MatchOperator == MatchOperator.Or)
{
break;
}
}
else
{
score = MatchScores.Mismatch;
break;
}
}
}
catch (Exception ex)
{
exception = ex;
}
return requestMatchResult.AddScore(GetType(), score, exception);
#endif
}
}