Skip to content

Commit

Permalink
Merge pull request #87 from endelwar/fix-foreach-after-filter
Browse files Browse the repository at this point in the history
Reindex collection array after filtering values
freekmurze authored Jun 11, 2021
2 parents 7e7b965 + 2016f55 commit bf62abc
Showing 2 changed files with 22 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/PeriodCollection.php
Original file line number Diff line number Diff line change
@@ -134,7 +134,7 @@ public function filter(Closure $closure): static
{
$collection = clone $this;

$collection->periods = array_filter($collection->periods, $closure);
$collection->periods = array_values(array_filter($collection->periods, $closure));

return $collection;
}
21 changes: 21 additions & 0 deletions tests/PeriodCollectionTest.php
Original file line number Diff line number Diff line change
@@ -277,4 +277,25 @@ public function filter()
$this->assertCount(1, $filtered);
$this->assertTrue($filtered[0]->equals($collection[0]));
}

/** @test */
public function it_loops_after_filter()
{
$collection = new PeriodCollection(
Period::make('2018-01-01', '2018-01-02'),
Period::make('2018-01-10', '2018-01-15'),
Period::make('2018-01-20', '2018-01-25'),
Period::make('2018-01-30', '2018-01-31')
);

$filtered = $collection->filter(function (Period $period) {
return $period->length() > 2;
});

$items = [];
foreach ($filtered as $item) {
$items[] = $item;
}
$this->assertEquals($filtered->count(), count($items));
}
}

0 comments on commit bf62abc

Please sign in to comment.