| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | using ArturRios.Util.RegularExpressions; |
| | | 4 | | using ArturRios.Util.Text; |
| | | 5 | | |
| | | 6 | | namespace ArturRios.Extensions; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Provides extension methods for working with strings, including validation helpers, |
| | | 10 | | /// parsing utilities, and convenient join operations. |
| | | 11 | | /// </summary> |
| | | 12 | | public static class StringExtensions |
| | | 13 | | { |
| | | 14 | | /// <summary> |
| | | 15 | | /// Options used by <see cref="ParseToObjectOrDefault{T}(string?)"/>: property names match regardless |
| | | 16 | | /// of case. |
| | | 17 | | /// </summary> |
| | 2 | 18 | | private static readonly JsonSerializerOptions CaseInsensitiveJson = new() { PropertyNameCaseInsensitive = true }; |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Checks if the string corresponds to a value declared by the specified enum type. |
| | | 22 | | /// </summary> |
| | | 23 | | /// <typeparam name="TEnum">The enum type to validate against.</typeparam> |
| | | 24 | | /// <param name="string">Input string value.</param> |
| | | 25 | | /// <param name="ignoreCase">Whether to ignore case during parsing (default true).</param> |
| | | 26 | | /// <returns>True if the string names a declared member of the enum; otherwise false.</returns> |
| | | 27 | | /// <remarks> |
| | | 28 | | /// Leading and trailing whitespace is tolerated, as <see cref="Enum.TryParse(Type, string, bool, out object)"/> |
| | | 29 | | /// trims it. A numeric string is only accepted when the number it denotes is a declared member. |
| | | 30 | | /// <see cref="Enum.TryParse(Type, string, bool, out object)"/> on its own accepts any number in the |
| | | 31 | | /// underlying type's range, so "999" parsed as a three-member enum used to be reported as valid. |
| | | 32 | | /// </remarks> |
| | | 33 | | public static bool IsValidEnumValue<TEnum>(this string @string, bool ignoreCase = true) where TEnum : Enum => |
| | 32 | 34 | | Enum.TryParse(typeof(TEnum), @string, ignoreCase, out var parsed) && Enum.IsDefined(typeof(TEnum), parsed!); |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Returns the string if it has value; otherwise returns the provided default. |
| | | 38 | | /// </summary> |
| | | 39 | | /// <param name="string">The input string.</param> |
| | | 40 | | /// <param name="defaultValue">Default value when input is null or empty.</param> |
| | | 41 | | /// <returns>The input string or the default value.</returns> |
| | | 42 | | public static string? ValueOrDefault(this string? @string, string? defaultValue = null) => |
| | 16 | 43 | | string.IsNullOrEmpty(@string) ? defaultValue : @string; |
| | | 44 | | |
| | | 45 | | /// <summary> |
| | | 46 | | /// Joins the sequence of strings using the provided separator. |
| | | 47 | | /// </summary> |
| | | 48 | | /// <param name="source">The sequence of strings to join.</param> |
| | | 49 | | /// <param name="separator">Separator to use (default ", ").</param> |
| | | 50 | | /// <returns>A single concatenated string.</returns> |
| | | 51 | | public static string JoinWith(this IEnumerable<string> source, string separator = ", ") => |
| | 10 | 52 | | string.Join(separator, source); |
| | | 53 | | |
| | | 54 | | /// <summary> |
| | | 55 | | /// Joins the sequence of items using the provided separator, converting each to string. |
| | | 56 | | /// </summary> |
| | | 57 | | /// <typeparam name="T">Item type.</typeparam> |
| | | 58 | | /// <param name="source">The sequence to join.</param> |
| | | 59 | | /// <param name="separator">Separator to use (default ", ").</param> |
| | | 60 | | /// <returns>A single concatenated string.</returns> |
| | | 61 | | public static string JoinWith<T>(this IEnumerable<T> source, string separator = ", ") => |
| | 16 | 62 | | string.Join(separator, source.Select(x => x?.ToString())); |
| | | 63 | | |
| | | 64 | | /// <summary> |
| | | 65 | | /// Provides validation helpers for the given non-null string. |
| | | 66 | | /// </summary> |
| | | 67 | | extension(string @string) |
| | | 68 | | { |
| | | 69 | | /// <summary> |
| | | 70 | | /// Checks whether the string contains at least one lowercase character. |
| | | 71 | | /// </summary> |
| | | 72 | | /// <returns>True if the string has a lowercase character; otherwise false.</returns> |
| | 10 | 73 | | public bool HasLowerChar() => RegexCollection.HasLowerChar().IsMatch(@string); |
| | | 74 | | |
| | | 75 | | /// <summary> |
| | | 76 | | /// Checks whether the string length is less than or equal to the given maximum. |
| | | 77 | | /// </summary> |
| | | 78 | | /// <param name="maxLength">Maximum allowed length.</param> |
| | | 79 | | /// <returns>True if within the max length; otherwise false.</returns> |
| | 16 | 80 | | public bool HasMaxLength(int maxLength) => !(@string.Length > maxLength); |
| | | 81 | | |
| | | 82 | | /// <summary> |
| | | 83 | | /// Checks whether the string length is greater than or equal to the given minimum. |
| | | 84 | | /// </summary> |
| | | 85 | | /// <param name="minLength">Minimum required length.</param> |
| | | 86 | | /// <returns>True if meets the min length; otherwise false.</returns> |
| | 16 | 87 | | public bool HasMinLength(int minLength) => !(@string.Length < minLength); |
| | | 88 | | |
| | | 89 | | /// <summary> |
| | | 90 | | /// Checks whether the string contains at least one numeric character. |
| | | 91 | | /// </summary> |
| | | 92 | | /// <returns>True if a number is present; otherwise false.</returns> |
| | 8 | 93 | | public bool HasNumber() => RegexCollection.HasNumber().IsMatch(@string); |
| | | 94 | | |
| | | 95 | | /// <summary> |
| | | 96 | | /// Checks whether the string contains at least one uppercase character. |
| | | 97 | | /// </summary> |
| | | 98 | | /// <returns>True if the string has an uppercase character; otherwise false.</returns> |
| | 10 | 99 | | public bool HasUpperChar() => RegexCollection.HasUpperChar().IsMatch(@string); |
| | | 100 | | |
| | | 101 | | /// <summary> |
| | | 102 | | /// Validates whether the string is a well-formed email address. |
| | | 103 | | /// </summary> |
| | | 104 | | /// <returns>True if the string is a valid email; otherwise false.</returns> |
| | | 105 | | /// <remarks> |
| | | 106 | | /// Delegates to <see cref="EmailAddress.IsValid"/>, so a mixed-case or internationalized domain is |
| | | 107 | | /// normalized before the syntax check rather than rejected outright. Applying |
| | | 108 | | /// <see cref="RegexCollection.Email"/> directly, as this used to, made the same address valid here |
| | | 109 | | /// and invalid there depending on which of the two a caller happened to reach for. |
| | | 110 | | /// </remarks> |
| | 28 | 111 | | public bool IsValidEmail() => EmailAddress.IsValid(@string); |
| | | 112 | | |
| | | 113 | | /// <summary> |
| | | 114 | | /// Trims leading and trailing whitespace, then trims the specified character from the ends of the |
| | | 115 | | /// result. |
| | | 116 | | /// </summary> |
| | | 117 | | /// <param name="charToTrim">Character to trim from both ends.</param> |
| | | 118 | | /// <returns>The trimmed string.</returns> |
| | | 119 | | /// <remarks> |
| | | 120 | | /// The two passes run in that order and once each, so whitespace uncovered by removing |
| | | 121 | | /// <paramref name="charToTrim"/> is left in place: <c>"- a -"</c> trimmed of <c>'-'</c> yields |
| | | 122 | | /// <c>" a "</c>. |
| | | 123 | | /// </remarks> |
| | | 124 | | public string TrimChar(char charToTrim) => |
| | 16 | 125 | | string.IsNullOrEmpty(@string) ? @string : @string.Trim().Trim(charToTrim); |
| | | 126 | | } |
| | | 127 | | |
| | | 128 | | /// <summary> |
| | | 129 | | /// Provides parsing helpers for a nullable string. |
| | | 130 | | /// </summary> |
| | | 131 | | extension(string? @string) |
| | | 132 | | { |
| | | 133 | | /// <summary> |
| | | 134 | | /// Parses the string to a boolean, or returns the provided default if parsing fails. |
| | | 135 | | /// </summary> |
| | | 136 | | /// <param name="defaultValue">Value to return when parsing fails.</param> |
| | | 137 | | /// <returns>The parsed boolean or the default value.</returns> |
| | | 138 | | public bool? ParseToBoolOrDefault(bool? defaultValue = null) => |
| | 24 | 139 | | bool.TryParse(@string, out var result) ? result : defaultValue; |
| | | 140 | | |
| | | 141 | | /// <summary> |
| | | 142 | | /// Parses the string to an integer, or returns the provided default if parsing fails. |
| | | 143 | | /// </summary> |
| | | 144 | | /// <param name="defaultValue">Value to return when parsing fails.</param> |
| | | 145 | | /// <returns>The parsed integer or the default value.</returns> |
| | | 146 | | /// <remarks> |
| | | 147 | | /// Parsing uses the invariant culture, so the result does not depend on the machine it runs on. |
| | | 148 | | /// Under the current culture, <c>"-5"</c> came back as the default on a machine set to a culture |
| | | 149 | | /// whose negative sign is not the ASCII hyphen-minus, such as fa-IR or ar-SA. Surrounding |
| | | 150 | | /// whitespace and a leading sign are accepted; group separators are not. |
| | | 151 | | /// </remarks> |
| | | 152 | | public int? ParseToIntOrDefault(int? defaultValue = null) => |
| | 42 | 153 | | int.TryParse(@string, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) |
| | 42 | 154 | | ? result |
| | 42 | 155 | | : defaultValue; |
| | | 156 | | |
| | | 157 | | /// <summary> |
| | | 158 | | /// Attempts to deserialize the JSON string to an object of type <typeparamref name="T" />. |
| | | 159 | | /// </summary> |
| | | 160 | | /// <typeparam name="T">Target reference type.</typeparam> |
| | | 161 | | /// <returns>An instance of T if deserialization succeeds; otherwise null.</returns> |
| | | 162 | | /// <remarks> |
| | | 163 | | /// Property names are matched without regard to case, so <c>{"name":"Ana"}</c> binds to a |
| | | 164 | | /// <c>Name</c> property. Matching only the exact case left every member at its default without |
| | | 165 | | /// any error, unlike <see cref="GenericExtensions.Clone{T}"/>, the HTTP helpers of ArturRios.Util |
| | | 166 | | /// and Microsoft.Extensions.Configuration binding, which all ignore case. |
| | | 167 | | /// </remarks> |
| | | 168 | | public T? ParseToObjectOrDefault<T>() where T : class |
| | | 169 | | { |
| | 30 | 170 | | if (string.IsNullOrEmpty(@string)) |
| | | 171 | | { |
| | 6 | 172 | | return null; |
| | | 173 | | } |
| | | 174 | | |
| | | 175 | | try |
| | | 176 | | { |
| | 24 | 177 | | return JsonSerializer.Deserialize<T>(@string, CaseInsensitiveJson); |
| | | 178 | | } |
| | 10 | 179 | | catch |
| | | 180 | | { |
| | 10 | 181 | | return null; |
| | | 182 | | } |
| | | 183 | | } |
| | | 184 | | } |
| | | 185 | | } |