using System.Text.RegularExpressions;
namespace AMWD.Net.Api.Cloudflare
{
///
/// Extension methods for s.
///
public static class StringExtensions
{
private static readonly Regex _idCheckRegex = new(@"^[0-9a-f]{32}$", RegexOptions.Compiled);
private static readonly Regex _emailCheckRegex = new(@"^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$", RegexOptions.Compiled);
///
/// Validate basic information for a Cloudflare ID.
///
///
/// An Cloudflare ID has max. 32 characters.
///
/// The string to check.
/// The is or any kind of whitespace.
/// The has more than 32 characters.
public static void ValidateCloudflareId(this string id)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentNullException(nameof(id));
id.ValidateLength(32, nameof(id));
if (!_idCheckRegex.IsMatch(id))
throw new ArgumentException("Invalid Cloudflare ID", nameof(id));
}
///
/// Validate basic information for a Cloudflare name.
///
///
/// An Cloudflare name has max. 253 characters.
///
/// The string to check.
/// The is or any kind of whitespace.
/// The has more than 253 characters.
public static void ValidateCloudflareName(this string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException(nameof(name));
name.ValidateLength(253, nameof(name));
}
///
/// Validate basic information for an email address.
///
/// The string to check.
/// The is or any kind of whitespace.
/// The does not match the regular expression pattern for an email address.
public static void ValidateCloudflareEmailAddress(this string emailAddress)
{
if (string.IsNullOrWhiteSpace(emailAddress))
throw new ArgumentNullException(nameof(emailAddress));
if (!_emailCheckRegex.IsMatch(emailAddress))
throw new ArgumentException("Invalid email address", nameof(emailAddress));
}
///
/// Validate the length of a string.
///
/// The string to check.
/// The max. length.
/// The name of the parameter to check.
/// The is longer than .
public static void ValidateLength(this string str, int length, string paramName)
{
if (str?.Length > length)
throw new ArgumentException($"The value of '{paramName}' is too long. Only {length} characters are allowed.");
}
}
}