| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="CharacterFilterTextSanitizer.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections.Generic; |
| | | 9 | | using System.Globalization; |
| | | 10 | | using System.Linq; |
| | | 11 | | using System.Text; |
| | | 12 | | |
| | | 13 | | namespace MyNet.Text.Sanitization; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Sanitizes text by preserving only allowed character classes. |
| | | 17 | | /// </summary> |
| | | 18 | | public sealed class CharacterFilterTextSanitizer(TextSanitizationOptions options) : ITextSanitizerTransform |
| | | 19 | | { |
| | 21 | 20 | | private readonly HashSet<char> _additionalAllowedCharacters = [.. options.AdditionalAllowedCharacters]; |
| | | 21 | | |
| | | 22 | | /// <inheritdoc/> |
| | | 23 | | public string Apply(string input, CultureInfo culture) |
| | | 24 | | { |
| | 60 | 25 | | ArgumentNullException.ThrowIfNull(input); |
| | 60 | 26 | | ArgumentNullException.ThrowIfNull(culture); |
| | | 27 | | |
| | 60 | 28 | | if (input.Length == 0) |
| | 3 | 29 | | return input; |
| | | 30 | | |
| | 57 | 31 | | var sb = new StringBuilder(input.Length); |
| | | 32 | | |
| | 690 | 33 | | foreach (var ch in input.Where(ch => _additionalAllowedCharacters.Contains(ch) |
| | 57 | 34 | | || (options.KeepLetters && char.IsLetter(ch)) |
| | 57 | 35 | | || (options.KeepDigits && char.IsDigit(ch)) |
| | 57 | 36 | | || (options.KeepWhitespace && char.IsWhiteSpace(ch)))) |
| | | 37 | | { |
| | 288 | 38 | | sb.Append(ch); |
| | | 39 | | } |
| | | 40 | | |
| | 57 | 41 | | return sb.ToString(); |
| | | 42 | | } |
| | | 43 | | } |
| | | 44 | | |