Skip to content

Commit

Permalink
Fix to ensure date ranges that are 1 day apart still get merged into …
Browse files Browse the repository at this point in the history
…a single range instead of splitting at this point.
  • Loading branch information
penance316 committed Oct 11, 2021
1 parent 255d7a7 commit 770839d
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 3 deletions.
3 changes: 2 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ language: php
php:
- '7.1'
- '7.2'
- '7.4'

before_script:
- composer install --prefer-dist --dev
script:
- ./vendor/bin/phpunit --configuration phpunit.xml.dist
- ./vendor/bin/phpunit --configuration phpunit.xml.dist
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ Available via composer
## Usage
```PHP

// Each date pair should consist of [earlierDate, laterDate].

$dates = [
[new DateTime('2019-04-01'), new DateTime('2019-05-01')],
[new DateTime('2019-05-01'), new DateTime('2019-06-01')],
Expand Down
10 changes: 8 additions & 2 deletions src/DateMerger.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,13 @@ public static function mergeRanges(array $ranges): array
foreach (array_slice($ranges, 1) as $range) {
$top = &$stack[count($stack) - 1];

if ($top[1] < $range[0]) {
//check if more than 1 day away otherwise can just be merged.
$interval = date_diff($top[1], $range[0]);

if ($interval->days === 1) {
// We assume the date ranges are always formatted [earlier, later]
$top[1] = $range[1];
} elseif ($top[1] < $range[0]) {
// Its a new one so push to stack
array_push($stack, $range);
} elseif
Expand All @@ -40,4 +46,4 @@ public static function mergeRanges(array $ranges): array

return $stack;
}
}
}
1 change: 1 addition & 0 deletions tests/DateMergerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public function testAllOverlapRanges()
[new DateTime('2019-06-01'), new DateTime('2019-07-01')],
[new DateTime('2019-07-01'), new DateTime('2019-08-01')],
[new DateTime('2019-08-01'), new DateTime('2019-09-01')],
[new DateTime('2019-09-02'), new DateTime('2018-09-05')],
];

$results = DateMerger::mergeRanges($dates);
Expand Down

0 comments on commit 770839d

Please sign in to comment.