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

[8.x] Track a loop variable for sequence and pass it with count to closure #37799

Merged
merged 4 commits into from
Jun 25, 2021
Merged
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
12 changes: 4 additions & 8 deletions src/Illuminate/Database/Eloquent/Factories/Sequence.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ class Sequence
*
* @var int
*/
protected $count;
public $count;

/**
* The current index of the sequence.
* The current index of the sequence iteration.
*
* @var int
*/
protected $index = 0;
public $index = 0;

/**
* Create a new sequence instance.
Expand All @@ -44,11 +44,7 @@ public function __construct(...$sequence)
*/
public function __invoke()
{
if ($this->index >= $this->count) {
$this->index = 0;
}

return tap(value($this->sequence[$this->index]), function () {
return tap(value($this->sequence[$this->index % $this->count], $this), function () {
$this->index = $this->index + 1;
});
}
Expand Down
7 changes: 7 additions & 0 deletions tests/Database/DatabaseEloquentFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,13 @@ public function test_sequences()
$this->assertCount(2, $user->roles->filter(function ($role) {
return $role->pivot->admin === 'N';
}));

$users = FactoryTestUserFactory::times(2)->sequence(function ($sequence) {
return ['name' => 'index: '.$sequence->index];
})->create();

$this->assertSame('index: 0', $users[0]->name);
$this->assertSame('index: 1', $users[1]->name);
}

public function test_resolve_nested_model_factories()
Expand Down