using System; using System.Linq; using System.Xml; using AnyOfTypes; using JetBrains.Annotations; using WireMock.Extensions; using WireMock.Models; using WireMock.Validation; #if !NETSTANDARD1_3 using Wmhelp.XPath2; #endif namespace WireMock.Matchers { /// /// XPath2Matcher /// /// public class XPathMatcher : IStringMatcher { private readonly AnyOf[] _patterns; /// public MatchBehaviour MatchBehaviour { get; } /// public bool ThrowException { get; } /// /// Initializes a new instance of the class. /// /// The patterns. public XPathMatcher([NotNull] params AnyOf[] patterns) : this(MatchBehaviour.AcceptOnMatch, false, patterns) { } /// /// Initializes a new instance of the class. /// /// The match behaviour. /// Throw an exception when the internal matching fails because of invalid input. /// The patterns. public XPathMatcher(MatchBehaviour matchBehaviour, bool throwException = false, [NotNull] params AnyOf[] patterns) { Check.NotNull(patterns, nameof(patterns)); MatchBehaviour = matchBehaviour; ThrowException = throwException; _patterns = patterns; } /// public double IsMatch(string input) { double match = MatchScores.Mismatch; if (input != null) { try { var nav = new XmlDocument { InnerXml = input }.CreateNavigator(); #if NETSTANDARD1_3 match = MatchScores.ToScore(_patterns.Select(p => true.Equals(nav.Evaluate($"boolean({p.GetPattern()})")))); #else match = MatchScores.ToScore(_patterns.Select(p => true.Equals(nav.XPath2Evaluate($"boolean({p.GetPattern()})")))); #endif } catch (Exception) { if (ThrowException) { throw; } } } return MatchBehaviourHelper.Convert(MatchBehaviour, match); } /// public AnyOf[] GetPatterns() { return _patterns; } /// public string Name => "XPathMatcher"; } }