diff --git a/.travis.yml b/.travis.yml index a1a4538..21be090 100644 --- a/.travis.yml +++ b/.travis.yml @@ -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 \ No newline at end of file + - ./vendor/bin/phpunit --configuration phpunit.xml.dist diff --git a/README.md b/README.md index 5dec02d..118aced 100644 --- a/README.md +++ b/README.md @@ -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')], diff --git a/src/DateMerger.php b/src/DateMerger.php index 0dbea29..469ebf6 100644 --- a/src/DateMerger.php +++ b/src/DateMerger.php @@ -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 @@ -40,4 +46,4 @@ public static function mergeRanges(array $ranges): array return $stack; } -} \ No newline at end of file +} diff --git a/tests/DateMergerTest.php b/tests/DateMergerTest.php index 38421af..a768617 100644 --- a/tests/DateMergerTest.php +++ b/tests/DateMergerTest.php @@ -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);