Skip to content

Commit

Permalink
Add non empty string method (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
WouterVeen authored Oct 23, 2023
1 parent 1ee1cdd commit 44bf2c9
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Fluent assertion methods, inspired by `webmozart/assert`:
- `true`
- `false`
- `notFalse`
- `nonEmptyString`
- `isInstanceOf`

### Example
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"@check:phpcs"
],
"check:phpstan": "phpstan analyse",
"check:phpmd": "phpmd src,tests text phpmd.xml.dist --suffixes=php",
"check:phpmd": "phpmd src,tests text phpmd.xml.dist --suffixes php",
"check:phpcs": "phpcs src tests",
"fix": "@fix:phpcbf",
"fix:phpcbf": "phpcbf src tests",
Expand Down
19 changes: 19 additions & 0 deletions src/Assert.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,25 @@ public static function string(mixed $value): string
return $value;
}

/**
* Assert value is a nonempty string
* @template T
* @phpstan-assert non-empty-string $value
*
* @param T $value
* @return T&non-empty-string
*/
public static function nonEmptyString(mixed $value): string
{
Assert::string($value);

if (strlen($value) === 0) {
throw new RuntimeException('Expecting value to be a non empty string');
}

return $value;
}

/**
* Assert value is boolean
* @template T
Expand Down
19 changes: 19 additions & 0 deletions tests/Unit/AssertTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,25 @@ public function testString(): void
static::assertSame('string', Assert::string('string'));
}

public function testNonEmptyStringNoStringFailure(): void
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Expecting value to be a string');
Assert::nonEmptyString(123); // @phpstan-ignore-line
}

public function testNonEmptyStringFailure(): void
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Expecting value to be a non empty string');
Assert::nonEmptyString('');
}

public function testNonEmptyString(): void
{
static::assertSame('string', Assert::nonEmptyString('string'));
}

public function testBoolean(): void
{
static::assertTrue(Assert::boolean(true));
Expand Down

0 comments on commit 44bf2c9

Please sign in to comment.