Skip to content

Commit

Permalink
Merge pull request #62 from spatie/period-collection-filter
Browse files Browse the repository at this point in the history
Add `filter` to `PeriodCollection`
  • Loading branch information
rubenvanassche authored Mar 31, 2020
2 parents 7d0fc6a + be17b4a commit 50395af
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

All notable changes to `period` will be documented in this file

## 1.5.0 - 2020-03-31

- Add `filter` to `PeriodCollection`

## 1.4.5 - 2020-02-05

- Fix for PeriodCollection::gaps() with excluded boundaries (#58)
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ $period->diff(Period ...$periods): PeriodCollection
$periodCollection->overlap(PeriodCollection ...$periodCollections): PeriodCollection
$periodCollection->overlapSingle(PeriodCollection $periodCollection): PeriodCollection
$periodCollection->map(Closure<Period> $closure): PeriodCollection
$periodCollection->filter(Closure<Period> $closure): PeriodCollection
$periodCollection->reduce(Closure<mixed, Period> $closure): mixed
```

Expand Down
14 changes: 14 additions & 0 deletions src/PeriodCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,20 @@ public function reduce(Closure $closure, $initial = null)
return $carry;
}

/**
* @param \Closure $closure
*
* @return static
*/
public function filter(Closure $closure): PeriodCollection
{
$collection = clone $this;

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

return $collection;
}

public function isEmpty(): bool
{
return count($this->periods) === 0;
Expand Down
17 changes: 17 additions & 0 deletions tests/PeriodCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Spatie\Period\Tests;

use DateTime;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;
use Spatie\Period\Boundaries;
Expand Down Expand Up @@ -227,4 +228,20 @@ public function reduce()

$this->assertEquals(4, $totalLength);
}

/** @test */
public function filter()
{
$collection = new PeriodCollection(
Period::make('2019-01-01', '2019-01-02'),
Period::make('2019-02-01', '2019-02-02')
);

$filtered = $collection->filter(function (Period $period) {
return $period->startsAt(new DateTime('2019-01-01'));
});

$this->assertCount(1, $filtered);
$this->assertTrue($filtered[0]->equals($collection[0]));
}
}

0 comments on commit 50395af

Please sign in to comment.