using System.Text.RegularExpressions; namespace Flypaper.Storage.Explanations; public static class ExplanationValidator { public static readonly TimeSpan MatchTimeout = TimeSpan.FromMilliseconds(250); public static Regex Compile(string pattern) => new(pattern, RegexOptions.NonBacktracking | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, MatchTimeout); public static string Pattern(string? pattern) { var value = pattern?.Trim(); if (string.IsNullOrEmpty(value)) { throw new ArgumentException("The pattern must not be empty."); } if (value.Length > ExplanationLimits.MaxPatternLength) { throw new ArgumentException($"The pattern must have at most {ExplanationLimits.MaxPatternLength} characters."); } try { Compile(value); } catch (ArgumentException exception) { throw new ArgumentException($"The pattern is not a valid regular expression: {exception.Message}"); } catch (NotSupportedException exception) { throw new ArgumentException($"The pattern uses a feature that is not supported (no lookarounds, backreferences or atomic groups): {exception.Message}"); } return value; } public static string Text(string? text) { var value = text?.Trim(); if (string.IsNullOrEmpty(value)) { throw new ArgumentException("The text must not be empty."); } if (value.Length > ExplanationLimits.MaxTextLength) { throw new ArgumentException($"The text must have at most {ExplanationLimits.MaxTextLength} characters."); } if (value.Any(char.IsControl)) { throw new ArgumentException("The text must be plain text without line breaks or control characters."); } return value; } public static string? Note(string? note) { var value = note?.Trim(); if (string.IsNullOrEmpty(value)) { return null; } if (value.Length > ExplanationLimits.MaxNoteLength) { throw new ArgumentException($"The note must have at most {ExplanationLimits.MaxNoteLength} characters."); } return value.Any(char.IsControl) ? throw new ArgumentException("The note must be plain text without control characters.") : value; } public static int Priority(int priority) => Math.Abs(priority) <= ExplanationLimits.MaxPriority ? priority : throw new ArgumentException($"The priority must be between -{ExplanationLimits.MaxPriority} and {ExplanationLimits.MaxPriority}."); }