Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[10.x] Add ulid testing helpers #48276

Merged
merged 3 commits into from Sep 4, 2023

Conversation

Jasonej
Copy link
Contributor

@Jasonej Jasonej commented Sep 2, 2023

This PR adds testing helpers to the generation of ULIDs to match what was introduced for UUIDs in #42619.

You can specify a ULID factory.

$ulid = Str::ulid();

Str::createUlidsUsing(fn() => $ulid);

Str::ulid() === $ulid; // true

You can freeze ULID generation which is equivalent to manually specifying a ULID factory as shown above, but doesn't require you to generate and capture a ULID first.

$ulid = Str::freezeUlids();

Str::ulid() === Str::ulid() === $ulid; // true

Str::createUlidsNormally();

When passing a closure it freezes only for the duration of that closure.

Str::freezeUlids(function ($ulid) {
    Str::ulid() === Str::ulid() === $ulid; // true
});

Str::ulid() === Str::ulid(); // false

You can also provide a sequence of ULIDs to return.

Str::createUlidsUsingSequence([
    $zeroth = Str::ulid(),
    $first = Str::ulid(),
]);

Str::ulid() === $zeroth;
Str::ulid() === $first;
Str::ulid(); // back to normally generated ULIDs.

You can skip indexes in a sequence to allow them to be normally generated.

Str::createUlidsUsingSequence([
    0 => ($zeroth = Str::ulid()),
    3 => ($third = Str::ulid()),
]);

Str::ulid() === $zeroth; // true
Str::ulid(); // normally generated
Str::ulid(); // normally generated
Str::ulid() === $third; // true

You can pass a closure to control what happens when there are no more ULIDs in the sequence.

Str::createUlidsUsingSequence([
    $zeroth = Str::ulid(),
    $first = Str::ulid(),
], fn() => throw new Exception('No more ULIDs in sequence'));

Str::ulid() === $zeroth; // true
Str::ulid() === $first; // true
Str::ulid(); // throws

This will impact skipped indexes as well though.

Str::createUlidsUsingSequence([
    0 => ($zeroth = Str::ulid()),
    3 => ($third = Str::ulid()),
], fn() => throw new Exception('No more ULIDs in sequence'));

Str::ulid() === $zeroth; // true
Str::ulid(); // throws

@taylorotwell taylorotwell merged commit c02a064 into laravel:10.x Sep 4, 2023
19 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants