-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathFilterQueryParser.cs
More file actions
832 lines (674 loc) · 33.8 KB
/
FilterQueryParser.cs
File metadata and controls
832 lines (674 loc) · 33.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using osu.Game.Screens.Select.Filter;
namespace osu.Game.Screens.Select
{
/// <summary>
/// Utility class used for parsing song select filter queries entered via the search box.
/// </summary>
public static class FilterQueryParser
{
private static readonly Regex query_syntax_regex = new Regex(
@"\b(?<key>\w+)(?<op>(!?(:|=)|(>|<)(:|=)?))(?<value>("".*?""[!]?)|(\S*))",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
internal static void ApplyQueries(FilterCriteria criteria, string query)
{
foreach (Match match in query_syntax_regex.Matches(query))
{
string key = match.Groups["key"].Value.ToLowerInvariant();
var op = parseOperator(match.Groups["op"].Value);
string value = match.Groups["value"].Value;
if (tryParseKeywordCriteria(criteria, key, value, op))
query = query.Replace(match.ToString(), "");
}
criteria.SearchText = query;
}
private static bool tryParseKeywordCriteria(FilterCriteria criteria, string key, string value, Operator op)
{
switch (key)
{
case "star":
case "stars":
case "sr":
return TryUpdateCriteriaRange(ref criteria.StarDifficulty, op, value, 0);
case "ar":
return TryUpdateCriteriaRange(ref criteria.ApproachRate, op, value);
case "dr":
case "hp":
return TryUpdateCriteriaRange(ref criteria.DrainRate, op, value);
case "cs":
return TryUpdateCriteriaRange(ref criteria.CircleSize, op, value);
case "od":
return TryUpdateCriteriaRange(ref criteria.OverallDifficulty, op, value);
case "bpm":
return TryUpdateCriteriaRange(ref criteria.BPM, op, value, 0.5f);
case "length":
return tryUpdateLengthRange(criteria, op, value);
case "lastplayed":
return tryUpdateDateAgoRange(ref criteria.LastPlayed, op, value);
case "ranked":
return tryUpdateRankedDateRange(ref criteria.DateRanked, op, value);
case "created":
case "submitted":
return tryUpdateRankedDateRange(ref criteria.DateSubmitted, op, value);
case "played":
if (!tryParseBool(value, out bool played))
return false;
// Unplayed beatmaps are filtered on DateTimeOffset.MinValue.
if (op == Operator.NotEqual)
played = !played;
if (played)
{
criteria.LastPlayed.Min = DateTimeOffset.MinValue;
criteria.LastPlayed.Max = DateTimeOffset.MaxValue;
criteria.LastPlayed.IsLowerInclusive = false;
}
else
{
criteria.LastPlayed.Min = DateTimeOffset.MinValue;
criteria.LastPlayed.Max = DateTimeOffset.MinValue;
criteria.LastPlayed.IsLowerInclusive = true;
criteria.LastPlayed.IsUpperInclusive = true;
}
return true;
case "divisor":
return TryUpdateCriteriaRange(ref criteria.BeatDivisor, op, value, tryParseInt);
case "status":
return TryUpdateCriteriaSet(ref criteria.OnlineStatus, op, value);
case "creator":
case "author":
case "mapper":
return TryUpdateCriteriaText(ref criteria.Creator, op, value);
case "artist":
return TryUpdateCriteriaText(ref criteria.Artist, op, value);
case "title":
return TryUpdateCriteriaText(ref criteria.Title, op, value);
case "diff":
return TryUpdateCriteriaText(ref criteria.DifficultyName, op, value);
case "source":
return TryUpdateCriteriaText(ref criteria.Source, op, value);
case "tag":
var tagFilter = new FilterCriteria.OptionalTextFilter();
TryUpdateCriteriaText(ref tagFilter, op, value);
criteria.UserTags.Add(tagFilter);
return true;
case "toprank":
return TryUpdateCriteriaSet(ref criteria.TopRank, op, value);
default:
return criteria.RulesetCriteria?.TryParseCustomKeywordCriteria(key, op, value) ?? false;
}
}
private static Operator parseOperator(string value)
{
switch (value)
{
case "=":
case ":":
return Operator.Equal;
case "!=":
case "!:":
return Operator.NotEqual;
case "<":
return Operator.Less;
case "<=":
case "<:":
return Operator.LessOrEqual;
case ">":
return Operator.Greater;
case ">=":
case ">:":
return Operator.GreaterOrEqual;
default:
throw new ArgumentOutOfRangeException(nameof(value), $"Unsupported operator {value}");
}
}
private static int getLengthScale(string value) =>
value.EndsWith("ms", StringComparison.Ordinal) ? 1 :
value.EndsWith('s') ? 1000 :
value.EndsWith('m') ? 60000 :
value.EndsWith('h') ? 3600000 : 1000;
private static bool tryParseFloatWithPoint(string value, out float result) =>
float.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out result);
private static bool tryParseDoubleWithPoint(string value, out double result) =>
double.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out result);
private static bool tryParseInt(string value, out int result) =>
int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out result);
private static bool tryParseBool(string value, out bool result)
{
switch (value)
{
case "1":
case "yes":
result = true;
return true;
case "0":
case "no":
result = false;
return true;
default:
return bool.TryParse(value, out result);
}
}
private static bool tryParseEnum<TEnum>(string value, out TEnum result) where TEnum : struct
{
// First try an exact match.
if (Enum.TryParse(value, true, out result))
return true;
// Then try a prefix match.
string? prefixMatch = Enum.GetNames(typeof(TEnum)).FirstOrDefault(name => name.StartsWith(value, true, CultureInfo.InvariantCulture));
if (prefixMatch == null)
return false;
return Enum.TryParse(prefixMatch, true, out result);
}
private static GroupCollection? tryMatchRegex(string value, string regex)
{
Match matches = Regex.Match(value, regex);
if (matches.Success)
return matches.Groups;
return null;
}
/// <summary>
/// Attempts to parse a keyword filter with the specified <paramref name="op"/> and textual <paramref name="value"/>.
/// If the value indicates a valid textual filter, the function returns <c>true</c> and the resulting data is stored into
/// <paramref name="textFilter"/>.
/// </summary>
/// <param name="textFilter">The <see cref="FilterCriteria.OptionalTextFilter"/> to store the parsed data into, if successful.</param>
/// <param name="op">
/// The operator for the keyword filter.
/// Only <see cref="Operator.Equal"/> is valid for textual filters.
/// </param>
/// <param name="value">The value of the keyword filter.</param>
public static bool TryUpdateCriteriaText(ref FilterCriteria.OptionalTextFilter textFilter, Operator op, string value)
{
switch (op)
{
case Operator.NotEqual:
textFilter.ExcludeTerm = true;
goto case Operator.Equal;
case Operator.Equal:
textFilter.SearchTerm = value;
return true;
default:
return false;
}
}
/// <summary>
/// Attempts to parse a keyword filter of type <see cref="float"/>
/// from the specified <paramref name="op"/> and <paramref name="val"/>.
/// If <paramref name="val"/> can be parsed as a <see cref="float"/>, the function returns <c>true</c>
/// and the resulting range constraint is stored into <paramref name="range"/>.
/// </summary>
/// <param name="range">
/// The <see cref="float"/>-typed <see cref="FilterCriteria.OptionalRange{T}"/>
/// to store the parsed data into, if successful.
/// </param>
/// <param name="op">The operator for the keyword filter.</param>
/// <param name="val">The value of the keyword filter.</param>
/// <param name="tolerance">Allowed tolerance of the parsed range boundary value.</param>
public static bool TryUpdateCriteriaRange(ref FilterCriteria.OptionalRange<float> range, Operator op, string val, float tolerance = 0.05f)
=> tryParseFloatWithPoint(val, out float value) && tryUpdateCriteriaRange(ref range, op, value, tolerance);
private static bool tryUpdateCriteriaRange(ref FilterCriteria.OptionalRange<float> range, Operator op, float value, float tolerance = 0.05f)
{
range.InvertRange = false;
switch (op)
{
default:
return false;
case Operator.NotEqual:
range.InvertRange = true;
goto case Operator.Equal;
case Operator.Equal:
range.Min = value - tolerance;
range.Max = value + tolerance;
if (tolerance == 0)
range.IsLowerInclusive = range.IsUpperInclusive = true;
break;
case Operator.Greater:
range.Min = value + tolerance;
break;
case Operator.GreaterOrEqual:
range.Min = value - tolerance;
break;
case Operator.Less:
range.Max = value - tolerance;
break;
case Operator.LessOrEqual:
range.Max = value + tolerance;
break;
}
return true;
}
/// <summary>
/// Attempts to parse a keyword filter of type <see cref="double"/>
/// from the specified <paramref name="op"/> and <paramref name="val"/>.
/// If <paramref name="val"/> can be parsed as a <see cref="double"/>, the function returns <c>true</c>
/// and the resulting range constraint is stored into <paramref name="range"/>.
/// </summary>
/// <param name="range">
/// The <see cref="double"/>-typed <see cref="FilterCriteria.OptionalRange{T}"/>
/// to store the parsed data into, if successful.
/// </param>
/// <param name="op">The operator for the keyword filter.</param>
/// <param name="val">The value of the keyword filter.</param>
/// <param name="tolerance">Allowed tolerance of the parsed range boundary value.</param>
public static bool TryUpdateCriteriaRange(ref FilterCriteria.OptionalRange<double> range, Operator op, string val, double tolerance = 0.05)
=> tryParseDoubleWithPoint(val, out double value) && tryUpdateCriteriaRange(ref range, op, value, tolerance);
private static bool tryUpdateCriteriaRange(ref FilterCriteria.OptionalRange<double> range, Operator op, double value, double tolerance = 0.05)
{
range.InvertRange = false;
switch (op)
{
default:
return false;
case Operator.NotEqual:
range.InvertRange = true;
goto case Operator.Equal;
case Operator.Equal:
range.Min = value - tolerance;
range.Max = value + tolerance;
if (tolerance == 0)
range.IsLowerInclusive = range.IsUpperInclusive = true;
break;
case Operator.Greater:
range.Min = value + tolerance;
break;
case Operator.GreaterOrEqual:
range.Min = value - tolerance;
if (tolerance == 0)
range.IsLowerInclusive = true;
break;
case Operator.Less:
range.Max = value - tolerance;
break;
case Operator.LessOrEqual:
range.Max = value + tolerance;
if (tolerance == 0)
range.IsUpperInclusive = true;
break;
}
return true;
}
/// <summary>
/// Used to determine whether the string value <paramref name="val"/> can be converted to type <typeparamref name="T"/>.
/// If conversion can be performed, the delegate returns <c>true</c>
/// and the conversion result is returned in the <c>out</c> parameter <paramref name="parsed"/>.
/// </summary>
/// <param name="val">The string value to attempt parsing for.</param>
/// <param name="parsed">The parsed value, if conversion is possible.</param>
public delegate bool TryParseFunction<T>(string val, out T parsed);
/// <summary>
/// Attempts to parse a keyword filter of type <typeparamref name="T"/>,
/// from the specified <paramref name="op"/> and <paramref name="val"/>.
/// If <paramref name="val"/> can be parsed into <typeparamref name="T"/> using <paramref name="parseFunction"/>, the function returns <c>true</c>
/// and the resulting range constraint is stored into <paramref name="range"/>.
/// </summary>
/// <param name="range">The <see cref="FilterCriteria.OptionalRange{T}"/> to store the parsed data into, if successful.</param>
/// <param name="op">The operator for the keyword filter.</param>
/// <param name="val">The value of the keyword filter.</param>
/// <param name="parseFunction">Function used to determine if <paramref name="val"/> can be converted to type <typeparamref name="T"/>.</param>
public static bool TryUpdateCriteriaRange<T>(ref FilterCriteria.OptionalRange<T> range, Operator op, string val, TryParseFunction<T> parseFunction)
where T : struct
=> parseFunction.Invoke(val, out var converted) && tryUpdateCriteriaRange(ref range, op, converted);
/// <summary>
/// Attempts to parse a keyword filter of type <typeparamref name="T"/>,
/// from the specified <paramref name="op"/> and <paramref name="filterValue"/>.
/// If <paramref name="filterValue"/> can be parsed successfully, the function returns <c>true</c>
/// and the resulting range constraint is stored into the <paramref name="range"/>'s expected values.
/// </summary>
/// <param name="range">The <see cref="FilterCriteria.OptionalSet{T}"/> to store the parsed data into, if successful.</param>
/// <param name="op">The operator for the keyword filter.</param>
/// <param name="filterValue">The value of the keyword filter.</param>
public static bool TryUpdateCriteriaSet<T>(ref FilterCriteria.OptionalSet<T> range, Operator op, string filterValue)
where T : struct, Enum
{
var matchingValues = new HashSet<T>();
if (filterValue.Contains(','))
{
string[] splitValues = filterValue.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
HashSet<T> parsedValues = new HashSet<T>();
foreach (string splitValue in splitValues)
{
if (!tryParseEnum<T>(splitValue, out var parsedValue))
return false;
parsedValues.Add(parsedValue);
}
if (op == Operator.Equal)
{
matchingValues.UnionWith(parsedValues);
}
else if (op == Operator.NotEqual)
{
matchingValues.UnionWith(Enum.GetValues<T>());
matchingValues.ExceptWith(parsedValues);
}
else
return false;
}
else
{
if (!tryParseEnum<T>(filterValue, out var pivotValue))
return false;
var allDefinedValues = Enum.GetValues<T>();
foreach (var val in allDefinedValues)
{
int compareResult = Comparer<T>.Default.Compare(val, pivotValue);
switch (op)
{
case Operator.Less:
if (compareResult < 0) matchingValues.Add(val);
break;
case Operator.LessOrEqual:
if (compareResult <= 0) matchingValues.Add(val);
break;
case Operator.Equal:
if (compareResult == 0) matchingValues.Add(val);
break;
case Operator.GreaterOrEqual:
if (compareResult >= 0) matchingValues.Add(val);
break;
case Operator.Greater:
if (compareResult > 0) matchingValues.Add(val);
break;
case Operator.NotEqual:
if (compareResult != 0) matchingValues.Add(val);
break;
default:
return false;
}
}
}
range.Values.IntersectWith(matchingValues);
return true;
}
private static bool tryUpdateCriteriaRange<T>(ref FilterCriteria.OptionalRange<T> range, Operator op, T value)
where T : struct
{
switch (op)
{
default:
return false;
case Operator.NotEqual:
range.InvertRange = true;
goto case Operator.Equal;
case Operator.Equal:
range.IsLowerInclusive = range.IsUpperInclusive = true;
range.Min = value;
range.Max = value;
break;
case Operator.Greater:
range.IsLowerInclusive = false;
range.Min = value;
break;
case Operator.GreaterOrEqual:
range.IsLowerInclusive = true;
range.Min = value;
break;
case Operator.Less:
range.IsUpperInclusive = false;
range.Max = value;
break;
case Operator.LessOrEqual:
range.IsUpperInclusive = true;
range.Max = value;
break;
}
return true;
}
private static bool tryUpdateLengthRange(FilterCriteria criteria, Operator op, string val)
{
List<string> parts = new List<string>();
GroupCollection? match = null;
match ??= tryMatchRegex(val, @"^((?<hours>\d+):)?(?<minutes>\d+):(?<seconds>\d+)$");
match ??= tryMatchRegex(val, @"^((?<hours>\d+(\.\d+)?)h)?((?<minutes>\d+(\.\d+)?)m)?((?<seconds>\d+(\.\d+)?)s)?$");
match ??= tryMatchRegex(val, @"^(?<seconds>\d+(\.\d+)?)$");
if (match == null)
return false;
if (match["seconds"].Success)
parts.Add(match["seconds"].Value + "s");
if (match["minutes"].Success)
parts.Add(match["minutes"].Value + "m");
if (match["hours"].Success)
parts.Add(match["hours"].Value + "h");
double totalLength = 0;
int minScale = 3600000;
for (int i = 0; i < parts.Count; i++)
{
string part = parts[i];
string partNoUnit = part.TrimEnd('m', 's', 'h');
if (!tryParseDoubleWithPoint(partNoUnit, out double length))
return false;
if (i != parts.Count - 1 && length >= 60)
return false;
if (i != 0 && partNoUnit.Contains('.'))
return false;
int scale = getLengthScale(part);
totalLength += length * scale;
minScale = Math.Min(minScale, scale);
}
return tryUpdateCriteriaRange(ref criteria.Length, op, totalLength, minScale / 2.0);
}
/// <summary>
/// This function is intended for parsing "days / months / years ago" type filters.
/// </summary>
private static bool tryUpdateDateAgoRange(ref FilterCriteria.OptionalRange<DateTimeOffset> dateRange, Operator op, string val)
{
switch (op)
{
case Operator.NotEqual:
case Operator.Equal:
// an equality or inequality filter is difficult to define for support here.
// if "3 months 2 days ago" means a single concrete time instant, such a filter is basically useless.
// if it means a range of 24 hours, then that is annoying to write and also comes with its own implications
// (does it mean "time instant 3 months 2 days ago, within 12 hours of tolerance either direction"?
// does it mean "the full calendar day, from midnight to midnight, 3 months 2 days ago"?)
// as such, for simplicity, just refuse to support this.
// same applies to inequality, but instead 24 hours would be need to be left out
return false;
// for the remaining operators, since the value provided to this function is an "ago" type value
// (as in, referring to some amount of time back),
// we'll want to flip the operator, such that `>5d` means "more than five days ago", as in "*before* five days ago",
// as intended by the user.
case Operator.Less:
op = Operator.Greater;
break;
case Operator.LessOrEqual:
op = Operator.GreaterOrEqual;
break;
case Operator.Greater:
op = Operator.Less;
break;
case Operator.GreaterOrEqual:
op = Operator.LessOrEqual;
break;
}
GroupCollection? match = null;
match ??= tryMatchRegex(val, @"^((?<years>\d+)y)?((?<months>\d+)M)?((?<days>\d+(\.\d+)?)d)?((?<hours>\d+(\.\d+)?)h)?((?<minutes>\d+(\.\d+)?)m)?((?<seconds>\d+(\.\d+)?)s)?$");
match ??= tryMatchRegex(val, @"^(?<days>\d+(\.\d+)?)$");
if (match == null)
return false;
DateTimeOffset? dateTimeOffset = null;
DateTimeOffset now = DateTimeOffset.Now;
try
{
List<string> keys = new List<string> { @"seconds", @"minutes", @"hours", @"days", @"months", @"years" };
foreach (string key in keys)
{
if (!match.TryGetValue(key, out var group) || !group.Success)
continue;
if (group.Success)
{
if (!tryParseDoubleWithPoint(group.Value, out double length))
return false;
switch (key)
{
case @"seconds":
dateTimeOffset = (dateTimeOffset ?? now).AddSeconds(-length);
break;
case @"minutes":
dateTimeOffset = (dateTimeOffset ?? now).AddMinutes(-length);
break;
case @"hours":
dateTimeOffset = (dateTimeOffset ?? now).AddHours(-length);
break;
case @"days":
dateTimeOffset = (dateTimeOffset ?? now).AddDays(-length);
break;
case @"months":
dateTimeOffset = (dateTimeOffset ?? now).AddMonths(-(int)length);
break;
case @"years":
dateTimeOffset = (dateTimeOffset ?? now).AddYears(-(int)length);
break;
}
}
}
}
catch (ArgumentOutOfRangeException)
{
dateTimeOffset = DateTimeOffset.MinValue.AddMilliseconds(1);
}
if (!dateTimeOffset.HasValue)
return false;
return tryUpdateCriteriaRange(ref dateRange, op, dateTimeOffset.Value);
}
/// <summary>
/// Helper function for building a UTC date from only the year, month and day.
/// UTC is used to keep consistent search results with osu!web.
/// </summary>
private static DateTimeOffset dateTimeOffsetFromDateOnly(int year, int month, int day) =>
new DateTimeOffset(year, month, day, 0, 0, 0, TimeSpan.Zero);
/// <summary>
/// Parses a string containing a ranked or submitted date filter.
/// Returns a boolean depending on whether parsing was successful or not.
/// Accepted dates are in the formats `yyyy`, `yyyy-mm` and `yyyy-mm-dd`.
/// Leading zeros are accepted. Numbers can be separated by `-`, `/`, or `.`
/// </summary>
/// <param name="dateRange">The <see cref="FilterCriteria.OptionalRange{DateTimeOffset}"/> to store the parsed data into, if successful.</param>
/// <param name="op">The operator of the filtering query</param>
/// <param name="val">The string value to attempt parsing for.</param>
private static bool tryUpdateRankedDateRange(ref FilterCriteria.OptionalRange<DateTimeOffset> dateRange, Operator op, string val)
{
GroupCollection? match = tryMatchRegex(val, @"^(?<year>\d+)([-/.](?<month>\d+)([-/.](?<day>\d+))?)?$");
if (match == null)
return false;
int? year = null;
int? month = null;
int? day = null;
List<string> keys = new List<string> { @"year", @"month", @"day" };
foreach (string key in keys)
{
if (!match.TryGetValue(key, out var group) || !group.Success)
continue;
if (group.Success)
{
if (!tryParseDoubleWithPoint(group.Value, out double value))
return false;
switch (key)
{
case @"year":
year = (int)value;
break;
case @"month":
month = (int)value;
break;
case @"day":
day = (int)value;
break;
}
}
}
if (year == null)
{
return false;
}
try
{
DateTimeOffset dateTimeOffset;
dateRange.InvertRange = false;
switch (op)
{
case Operator.Less:
month ??= 1;
day ??= 1;
dateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value);
return tryUpdateCriteriaRange(ref dateRange, op, dateTimeOffset);
case Operator.LessOrEqual:
if (month == null)
{
month = 1;
day = 1;
dateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value).AddYears(1);
return tryUpdateCriteriaRange(ref dateRange, Operator.Less, dateTimeOffset);
}
if (day == null)
{
day = 1;
dateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value).AddMonths(1);
return tryUpdateCriteriaRange(ref dateRange, Operator.Less, dateTimeOffset);
}
dateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value).AddDays(1);
return tryUpdateCriteriaRange(ref dateRange, Operator.Less, dateTimeOffset);
case Operator.GreaterOrEqual:
month ??= 1;
day ??= 1;
dateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value);
return tryUpdateCriteriaRange(ref dateRange, op, dateTimeOffset);
case Operator.Greater:
if (month == null)
{
month = 1;
day = 1;
dateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value).AddYears(1);
return tryUpdateCriteriaRange(ref dateRange, Operator.GreaterOrEqual, dateTimeOffset);
}
if (day == null)
{
day = 1;
dateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value).AddMonths(1);
return tryUpdateCriteriaRange(ref dateRange, Operator.GreaterOrEqual, dateTimeOffset);
}
dateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value).AddDays(1);
return tryUpdateCriteriaRange(ref dateRange, Operator.GreaterOrEqual, dateTimeOffset);
case Operator.NotEqual:
dateRange.InvertRange = true;
goto case Operator.Equal;
case Operator.Equal:
DateTimeOffset minDateTimeOffset;
DateTimeOffset maxDateTimeOffset;
if (month == null)
{
month = 1;
day = 1;
minDateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value);
maxDateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value).AddYears(1);
return tryUpdateCriteriaRange(ref dateRange, Operator.GreaterOrEqual, minDateTimeOffset)
&& tryUpdateCriteriaRange(ref dateRange, Operator.Less, maxDateTimeOffset);
}
if (day == null)
{
day = 1;
minDateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value);
maxDateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value).AddMonths(1);
return tryUpdateCriteriaRange(ref dateRange, Operator.GreaterOrEqual, minDateTimeOffset)
&& tryUpdateCriteriaRange(ref dateRange, Operator.Less, maxDateTimeOffset);
}
minDateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value);
maxDateTimeOffset = dateTimeOffsetFromDateOnly(year.Value, month.Value, day.Value).AddDays(1);
return tryUpdateCriteriaRange(ref dateRange, Operator.GreaterOrEqual, minDateTimeOffset)
&& tryUpdateCriteriaRange(ref dateRange, Operator.Less, maxDateTimeOffset);
default:
return false;
}
}
catch (ArgumentOutOfRangeException)
{
return false;
}
}
}
}