From 2eaf80b1bd09f57954c018fc1ab167c6aec71721 Mon Sep 17 00:00:00 2001 From: Clemens Schwaighofer Date: Tue, 4 Jul 2023 11:46:34 +0900 Subject: [PATCH] new Combined\DateTime method dateRangeHasWeekend --- src/Combined/DateTime.php | 25 ++++++++ .../Combined/CoreLibsCombinedDateTimeTest.php | 64 +++++++++++++++++++ 2 files changed, 89 insertions(+) diff --git a/src/Combined/DateTime.php b/src/Combined/DateTime.php index c1f1614..2791788 100644 --- a/src/Combined/DateTime.php +++ b/src/Combined/DateTime.php @@ -452,6 +452,31 @@ class DateTime return $days; } } + + /** + * check if a weekend day (sat/sun) is in the given date range + * Can have time too, but is not needed + * + * @param string $start_date Y-m-d + * @param string $end_date Y-m-d + * @return bool True for has weekend, False for has not + */ + public static function dateRangeHasWeekend( + string $start_date, + string $end_date, + ): bool { + $dd_start = new \DateTime($start_date); + $dd_end = new \DateTime($end_date); + if ( + // starts with a weekend + $dd_start->format('N') >= 6 || + // start day plus diff will be 6 and so fall into a weekend + ((int)$dd_start->format('w') + $dd_start->diff($dd_end)->days) >= 6 + ) { + return true; + } + return false; + } } // __END__ diff --git a/test/phpunit/Combined/CoreLibsCombinedDateTimeTest.php b/test/phpunit/Combined/CoreLibsCombinedDateTimeTest.php index 2dd2480..ddc03ca 100644 --- a/test/phpunit/Combined/CoreLibsCombinedDateTimeTest.php +++ b/test/phpunit/Combined/CoreLibsCombinedDateTimeTest.php @@ -458,6 +458,47 @@ final class CoreLibsCombinedDateTimeTest extends TestCase ]; } + /** + * Undocumented function + * + * @return array + */ + public function dateRangeHasWeekendProvider(): array + { + return [ + 'no weekend' => [ + '2023-07-03', + '2023-07-04', + false + ], + 'start weekend sat' => [ + '2023-07-01', + '2023-07-04', + true + ], + 'start weekend sun' => [ + '2023-07-02', + '2023-07-04', + true + ], + 'end weekend sat' => [ + '2023-07-03', + '2023-07-08', + true + ], + 'end weekend sun' => [ + '2023-07-03', + '2023-07-09', + true + ], + 'long period > 6 days' => [ + '2023-07-03', + '2023-07-27', + true + ] + ]; + } + /** * date string convert test * @@ -780,6 +821,29 @@ final class CoreLibsCombinedDateTimeTest extends TestCase $output ); } + + /** + * Undocumented function + * + * @covers ::dateRangeHasWeekend + * @dataProvider dateRangeHasWeekendProvider + * @testdox dateRangeHasWeekend $start_date and $end_date are expected weekend $expected [$_dataName] + * + * @param string $start_date + * @param string $end_date + * @param bool $expected + * @return void + */ + public function testDateRangeHasWeekend( + string $start_date, + string $end_date, + bool $expected + ): void { + $this->assertEquals( + $expected, + \CoreLibs\Combined\DateTime::dateRangeHasWeekend($start_date, $end_date) + ); + } } // __END__