From ee38f12b79731edcbee57873d384946a9cf7b2f8 Mon Sep 17 00:00:00 2001 From: Corey Taylor Date: Sat, 14 Jun 2025 17:02:20 -0500 Subject: [PATCH] Add ChronosPeriod which returns Chronos instances from DatePeriod --- phpstan.neon | 4 ++ src/ChronosPeriod.php | 83 ++++++++++++++++++++++++++++ tests/TestCase/ChronosPeriodTest.php | 38 +++++++++++++ 3 files changed, 125 insertions(+) create mode 100644 src/ChronosPeriod.php create mode 100644 tests/TestCase/ChronosPeriodTest.php diff --git a/phpstan.neon b/phpstan.neon index 68575ca4..4dcb07f0 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -13,3 +13,7 @@ parameters: message: "#^Call to an undefined static method DateTimeImmutable\\:\\:createFromTimestamp\\(\\)\\.$#" count: 1 path: src/Chronos.php + - + message: "#with generic class DatePeriod but does not specify its types: TDate, TEnd, TRecurrences$#" + count: 1 + path: src/ChronosPeriod.php diff --git a/src/ChronosPeriod.php b/src/ChronosPeriod.php new file mode 100644 index 00000000..62e5f9f9 --- /dev/null +++ b/src/ChronosPeriod.php @@ -0,0 +1,83 @@ + + */ +class ChronosPeriod implements Iterator +{ + /** + * @var \Iterator + */ + protected Iterator $iterator; + + /** + * @param \DatePeriod $period + */ + public function __construct(DatePeriod $period) + { + /** @var \Iterator $iterator */ + $iterator = $period->getIterator(); + $this->iterator = $iterator; + } + + /** + * @return \Cake\Chronos\Chronos + */ + public function current(): Chronos + { + return new Chronos($this->iterator->current()); + } + + /** + * @return int + */ + public function key(): int + { + return $this->iterator->key(); + } + + /** + * @return void + */ + public function next(): void + { + $this->iterator->next(); + } + + /** + * @return void + */ + public function rewind(): void + { + $this->iterator->rewind(); + } + + /** + * @return bool + */ + public function valid(): bool + { + return $this->iterator->valid(); + } +} diff --git a/tests/TestCase/ChronosPeriodTest.php b/tests/TestCase/ChronosPeriodTest.php new file mode 100644 index 00000000..8bb832ce --- /dev/null +++ b/tests/TestCase/ChronosPeriodTest.php @@ -0,0 +1,38 @@ + $value) { + $output[$key] = $value; + } + $this->assertCount(4, $output); + $this->assertInstanceOf(Chronos::class, $output[0]); + $this->assertSame('2025-01-01 00:00:00', $output[0]->format('Y-m-d H:i:s')); + $this->assertInstanceOf(Chronos::class, $output[1]); + $this->assertSame('2025-01-01 01:00:00', $output[1]->format('Y-m-d H:i:s')); + } +}