| | 1 | | using Fluorite.Strainer.Models.Filtering.Terms; |
| | 2 | | using System.Text.RegularExpressions; |
| | 3 | |
|
| | 4 | | namespace Fluorite.Strainer.Services.Filtering; |
| | 5 | |
|
| | 6 | | public class FilterTermSectionsParser : IFilterTermSectionsParser |
| | 7 | | { |
| | 8 | | private readonly IConfigurationFilterOperatorsProvider _filterOperatorsConfigurationProvider; |
| | 9 | |
|
| 22 | 10 | | public FilterTermSectionsParser( |
| 22 | 11 | | IConfigurationFilterOperatorsProvider filterOperatorsConfigurationProvider) |
| | 12 | | { |
| 22 | 13 | | _filterOperatorsConfigurationProvider = Guard.Against.Null(filterOperatorsConfigurationProvider); |
| 22 | 14 | | } |
| | 15 | |
|
| | 16 | | public FilterTermSections Parse(string input) |
| | 17 | | { |
| 18 | 18 | | Guard.Against.Null(input); |
| | 19 | |
|
| | 20 | | // Order by longest operator to ensure we first try to match the longest ones |
| | 21 | | // as shorter operators are contained within longer ones and would be matched |
| | 22 | | // first, but only partially, leaving out the rest of operator. |
| 18 | 23 | | var symbols = _filterOperatorsConfigurationProvider |
| 18 | 24 | | .GetFilterOperators() |
| 18 | 25 | | .Keys |
| 226 | 26 | | .OrderByDescending(s => s.Length) |
| 18 | 27 | | .ToArray(); |
| 18 | 28 | | if (!symbols.Any()) |
| | 29 | | { |
| 1 | 30 | | throw new InvalidOperationException("No filter operators found."); |
| | 31 | | } |
| | 32 | |
|
| 243 | 33 | | var splitPattern = string.Join("|", symbols.Select(s => $"({Regex.Escape(s)})")); |
| 17 | 34 | | var substrings = Regex.Split(input, splitPattern, RegexOptions.None, TimeSpan.FromMilliseconds(100)); |
| | 35 | |
|
| 17 | 36 | | return substrings.Length switch |
| 17 | 37 | | { |
| 3 | 38 | | <= 2 => new FilterTermSections |
| 3 | 39 | | { |
| 3 | 40 | | Names = substrings.FirstOrDefault(), |
| 3 | 41 | | OperatorSymbol = string.Empty, |
| 3 | 42 | | Values = string.Empty, |
| 3 | 43 | | }, |
| 14 | 44 | | >= 3 => new FilterTermSections |
| 14 | 45 | | { |
| 14 | 46 | | Names = substrings[0], |
| 14 | 47 | | OperatorSymbol = substrings[1], |
| 14 | 48 | | Values = substrings[2], |
| 14 | 49 | | }, |
| 17 | 50 | | }; |
| | 51 | | } |
| | 52 | | } |