Skip to content

Commit

Permalink
feat: add toBeUlid() expectation
Browse files Browse the repository at this point in the history
  • Loading branch information
lalcebo committed Dec 12, 2024
1 parent 9688b83 commit ca3acb6
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Mixins/Expectation.php
Original file line number Diff line number Diff line change
Expand Up @@ -1131,6 +1131,22 @@ public function toBeUuid(string $message = ''): self
return $this;
}

/**
* Asserts that the value is ULID.
*
* @return self<TValue>
*/
public function toBeUlid(string $message = ''): self
{
if (! is_string($this->value)) {
InvalidExpectationValue::expected('string');
}

Assert::assertTrue(Str::isUlid($this->value), $message);

return $this;
}

/**
* Asserts that the value is between 2 specified values
*
Expand Down
8 changes: 8 additions & 0 deletions src/Support/Str.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,14 @@ public static function isUuid(string $value): bool
return preg_match('/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iD', $value) > 0;
}

/**
* Determine if a given value is a valid ULID.
*/
public static function isUlid(string $value): bool
{
return preg_match('/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/iD', $value) > 0;
}

/**
* Creates a describe block as `$describeDescription` → `$testDescription` format.
*
Expand Down
24 changes: 24 additions & 0 deletions tests/Features/Expect/toBeUlid.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

use Pest\Exceptions\InvalidExpectationValue;
use PHPUnit\Framework\ExpectationFailedException;

test('failures with wrong type', function () {
expect([])->toBeUlid();
})->throws(InvalidExpectationValue::class, 'Invalid expectation value type. Expected [string].');

test('pass', function () {
expect('01JEWKD14JZJC6GKVQG8CAF93G')->toBeUlid();
});

test('failures', function () {
expect('foo')->toBeUlid();
})->throws(ExpectationFailedException::class);

test('failures with message', function () {
expect('bar')->toBeUlid('oh no!');
})->throws(ExpectationFailedException::class, 'oh no!');

test('not failures', function () {
expect('foo')->not->toBeUlid();
});

0 comments on commit ca3acb6

Please sign in to comment.