IsNullOrWhiteSpace Extension method for HtmlEncodedString (#13747)

* Add IsNullOrWhiteSpace Extension method

IsNullOrWhiteSpace extension method for IHtmlEncodedString

* Move extension method

* Add a UnitTest for the IsNullOrWhiteSpace extension method

* Update unit test

(cherry picked from commit 9771e77243)
This commit is contained in:
Erik-Jan Westendorp
2023-03-02 11:57:43 +01:00
committed by Sebastiaan Janssen
parent 84d81b20ef
commit 010ea5a2aa
2 changed files with 45 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
using System.Diagnostics.CodeAnalysis;
using Umbraco.Cms.Core.Strings;
namespace Umbraco.Extensions;
public static class HtmlEncodedStringExtensions
{
/// <summary>
/// Checks if the specified <see cref="IHtmlEncodedString" /> is <c>null</c> or only contains whitespace, optionally after all HTML tags have been stripped/removed.
/// </summary>
/// <param name="htmlEncodedString">The encoded HTML string.</param>
/// <param name="stripHtml">If set to <c>true</c> strips/removes all HTML tags.</param>
/// <returns>
/// Returns <c>true</c> if the HTML string is <c>null</c> or only contains whitespace, optionally after all HTML tags have been stripped/removed.
/// </returns>
public static bool IsNullOrWhiteSpace([NotNullWhen(false)] this IHtmlEncodedString? htmlEncodedString, bool stripHtml = false)
=> (htmlEncodedString?.ToHtmlString() is var htmlString && string.IsNullOrWhiteSpace(htmlString)) ||
(stripHtml && string.IsNullOrWhiteSpace(htmlString.StripHtml()));
}

View File

@@ -0,0 +1,26 @@
using Moq;
using NUnit.Framework;
using Umbraco.Cms.Core.Strings;
using Umbraco.Extensions;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Extensions;
[TestFixture]
public class HtmlEncodedStringExtensionsTests
{
[TestCase(null, false, true)]
[TestCase("", false, true)]
[TestCase(" ", false, true)]
[TestCase("This is a non-empty string", false, false)]
[TestCase("<p>This is a non-empty string</p>", true,false)]
[TestCase("<p>This is a non-empty string</p>", false,false)]
[TestCase("<p></p>", true, true)]
[TestCase("<p></p>", false, false)]
public void IsNullOrWhiteSpace(string? htmlString, bool stripHtml, bool expectedResult)
{
var htmlEncodedString = htmlString == null ? null : Mock.Of<IHtmlEncodedString>(x => x.ToHtmlString() == htmlString);
var result = htmlEncodedString.IsNullOrWhiteSpace(stripHtml: stripHtml);
Assert.AreEqual(expectedResult, result);
}
}