Skip to content

Commit b5f239a

Browse files
Merge pull request #5 from swisnl/feature/covering
Add getCoveringDateRange method on DateRangeSet
2 parents 60f2fef + f415b0a commit b5f239a

3 files changed

Lines changed: 50 additions & 1 deletion

File tree

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
77

88
## [Unreleased]
99

10-
* Nothing yet.
10+
* Add `DateRangeSet::getCoveringDateRange()` method to get the minimal date
11+
range covering all ranges in the set.
1112

1213
## [1.1.0] - 2025-11-21
1314

src/DateRangeSet.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,29 @@ public function isNotEmpty(): bool
344344
return ! $this->isEmpty();
345345
}
346346

347+
/**
348+
* Get the smallest DateRange that covers all date ranges in the set.
349+
*
350+
* This method returns a DateRange that covers the entire span of the date
351+
* ranges in the set. If the set is empty, it will return null.
352+
*/
353+
public function getCoveringDateRange(): ?DateRange
354+
{
355+
if ($this->isEmpty()) {
356+
return null;
357+
}
358+
359+
/** @var \Swis\DateRange\DateRange $firstRange */
360+
$firstRange = $this->dateRanges->first();
361+
/** @var \Swis\DateRange\DateRange $lastRange */
362+
$lastRange = $this->dateRanges->last();
363+
364+
return DateRange::make(
365+
$firstRange->getStartDate(),
366+
$lastRange->getEndDate(),
367+
);
368+
}
369+
347370
/**
348371
* Convert the set to a collection of CarbonImmutable dates.
349372
*

tests/DateRangeSetTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,3 +297,28 @@
297297
],
298298
],
299299
]);
300+
301+
it('gets the covering date range', function (array $ranges, ?array $coveringRange) {
302+
$dateRangeSet = DateRangeSet::fromArray($ranges);
303+
304+
expect($dateRangeSet->getCoveringDateRange()?->toArray())->toEqual($coveringRange);
305+
})->with([
306+
'simple' => [
307+
[
308+
['2021-01-01', '2021-02-15'],
309+
['2021-03-01', '2021-03-31'],
310+
],
311+
['2021-01-01', '2021-03-31'],
312+
],
313+
'with nulls' => [
314+
[
315+
[null, '2021-02-15'],
316+
['2021-03-01', null],
317+
],
318+
[null, null],
319+
],
320+
'empty set' => [
321+
[],
322+
null,
323+
],
324+
]);

0 commit comments

Comments
 (0)