From 55a65211d1e7dd2d76c928407fda0f25bc33d3e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexander=20Rie=C3=9F?= Date: Wed, 27 May 2026 11:42:02 +0200 Subject: [PATCH] Add isEmpty method --- src/Str.php | 16 ++++++++++++++++ tests/StrTest.php | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/src/Str.php b/src/Str.php index 0dac0bb..3f6a481 100644 --- a/src/Str.php +++ b/src/Str.php @@ -2,6 +2,8 @@ namespace ipl\Stdlib; +use Stringable; + /** * Collection of string manipulation functions */ @@ -90,4 +92,18 @@ public static function trimSplit(?string $subject, string $delimiter = ',', ?int return array_map('trim', $exploded); } + + /** + * Check if the given string is empty + * + * Null is considered empty and strings are trimmed before checking. + * + * @param Stringable|string|null $subject + * + * @return bool + */ + public static function isEmpty(Stringable|string|null $subject): bool + { + return $subject === null || trim((string) $subject) === ''; + } } diff --git a/tests/StrTest.php b/tests/StrTest.php index d4c7075..b1c3369 100644 --- a/tests/StrTest.php +++ b/tests/StrTest.php @@ -47,6 +47,51 @@ public function testStartsWithReturnsFalseIfStringDoesNotStartWithTheSpecifiedSu $this->assertFalse(Str::startsWith('FOOBAR', 'foo', true)); } + public function testIsEmptyReturnsTrueForNull() + { + $this->assertTrue(Str::isEmpty(null)); + } + + public function testIsEmptyReturnsTrueForEmptyString() + { + $this->assertTrue(Str::isEmpty('')); + } + + public function testIsEmptyReturnsTrueForStringWithLeadingAndTrailingWhitespace() + { + $this->assertTrue(Str::isEmpty(' ')); + } + + public function testIsEmptyReturnsTrueForStringWithOnlyWhitespace() + { + $this->assertTrue(Str::isEmpty("\t\n")); + } + + public function testIsEmptyReturnsFalseForZero() + { + $this->assertFalse(Str::isEmpty('0')); + } + + public function testIsEmptyReturnsFalseForNonEmptyString() + { + $this->assertFalse(Str::isEmpty('Warning')); + } + + public function testIsEmptyReturnsFalseForStringWithContentAndSurroundingWhitespace() + { + $this->assertFalse(Str::isEmpty(' Warning ')); + } + + public function testIsEmptyReturnsFalseForUtf8String() + { + $this->assertFalse(Str::isEmpty('接続エラー')); + } + + public function testIsEmptyReturnsFalseForUtf8StringWithSurroundingWhitespace() + { + $this->assertFalse(Str::isEmpty(' 接続エラー ')); + } + public function testSymmetricSplitReturnsArrayPaddedToTheSizeSpecifiedByLimitUsingNullAsValueByDefault() { $this->assertSame(['foo', 'bar', null, null], Str::symmetricSplit('foo,bar', ',', 4));