Skip to content

Commit

Permalink
Add period collection intersect
Browse files Browse the repository at this point in the history
  • Loading branch information
brendt committed Apr 19, 2019
1 parent 5628d25 commit 1c2af9d
Show file tree
Hide file tree
Showing 4 changed files with 63 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.2.0 - 2019-04-19

- Add period collection intersect

## 1.1.3 - 2019-04-05

- Even better docblock support for static return types
Expand Down
10 changes: 10 additions & 0 deletions src/Period.php
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,16 @@ public function diff(Period ...$periods): PeriodCollection
return $collection;
}

/**
* @param \Spatie\Period\Period $period
*
* @return static
*/
public function intersect(Period $period): Period
{

}

public function getPrecisionMask(): int
{
return $this->precisionMask;
Expand Down
17 changes: 17 additions & 0 deletions src/PeriodCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,23 @@ public function gaps(): PeriodCollection
return $boundaries->diff(...$this);
}

public function intersect(Period $intersection): PeriodCollection
{
$intersected = new PeriodCollection();

foreach ($this as $period) {
$overlap = $intersection->overlapSingle($period);

if ($overlap === null) {
continue;
}

$intersected[] = $overlap;
}

return $intersected;
}

public function isEmpty(): bool
{
return count($this->periods) === 0;
Expand Down
32 changes: 32 additions & 0 deletions tests/PeriodCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,4 +141,36 @@ public function it_can_determine_whether_a_period_has_a_date()
$this->assertFalse($period->contains(new DateTimeImmutable('2017-12-31')));
$this->assertFalse($period->contains(new DateTimeImmutable('2018-02-01')));
}

/**
* @test
*
* A [========================]
* B [================]
* C [=====================]
* D [=====]
*
* LIMIT [===============]
*
* A [===============]
* B [========]
* C [=======]
*/
public function intersect_test()
{
$collection = new PeriodCollection(
Period::make('2019-01-05', '2019-01-15'),
Period::make('2019-01-01', '2019-01-10'),
Period::make('2019-01-10', '2019-01-15'),
Period::make('2019-02-01', '2019-02-15'),
);

$intersect = $collection->intersect(Period::make('2019-01-09', '2019-01-11'));

$this->assertCount(3, $intersect);

$this->assertTrue($intersect[0]->equals(Period::make('2019-01-09', '2019-01-11')));
$this->assertTrue($intersect[1]->equals(Period::make('2019-01-09', '2019-01-10')));
$this->assertTrue($intersect[2]->equals(Period::make('2019-01-10', '2019-01-11')));
}
}

0 comments on commit 1c2af9d

Please sign in to comment.