Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace ipl\Stdlib;

use Stringable;

/**
* Collection of string manipulation functions
*/
Expand Down Expand Up @@ -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) === '';
}
}
45 changes: 45 additions & 0 deletions tests/StrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
Loading