diff --git a/src/Common/Date.php b/src/Common/Date.php index f78241fe..6ff17c2d 100644 --- a/src/Common/Date.php +++ b/src/Common/Date.php @@ -18,6 +18,13 @@ private function __construct(DateTimeImmutable $start, DateTimeImmutable|null $e $this->end = $end; } + public static function create( + DateTimeImmutable $start, + DateTimeImmutable $end = null, + ): self { + return new self($start, $end); + } + /** * @param DateJson $array * @@ -53,4 +60,19 @@ public function isRange(): bool { return $this->end !== null; } + + public function withStart(DateTimeImmutable $start): self + { + return new self($start, $this->end); + } + + public function withEnd(DateTimeImmutable $end): self + { + return new self($this->start, $end); + } + + public function withoutEnd(): self + { + return new self($this->start, null); + } } diff --git a/tests/Unit/Common/DateTest.php b/tests/Unit/Common/DateTest.php new file mode 100644 index 00000000..43f77881 --- /dev/null +++ b/tests/Unit/Common/DateTest.php @@ -0,0 +1,72 @@ + "2021-01-01", + "end" => "2021-12-31", + ]; + + $date = Date::fromArray($array); + $this->assertEquals($array, $date->toArray()); + } + + public function test_create_date(): void + { + $start = new DateTimeImmutable("2021-01-01"); + $date = Date::create($start); + + $this->assertSame($start, $date->start()); + $this->assertNull($date->end()); + $this->assertFalse($date->isRange()); + } + + public function test_create_range(): void + { + $start = new DateTimeImmutable("2021-01-01"); + $end = new DateTimeImmutable("2021-12-31"); + $date = Date::create($start, $end); + + $this->assertSame($start, $date->start()); + $this->assertSame($end, $date->end()); + $this->assertTrue($date->isRange()); + } + + public function test_change_start(): void + { + $oldStart = new DateTimeImmutable("2021-01-01"); + $newStart = new DateTimeImmutable("2022-01-01"); + + $date = Date::create($oldStart)->withStart($newStart); + + $this->assertSame($newStart, $date->start()); + } + + public function test_change_end(): void + { + $start = new DateTimeImmutable("2021-01-01"); + $end = new DateTimeImmutable("2022-01-01"); + + $date = Date::create($start)->withEnd($end); + + $this->assertSame($end, $date->end()); + } + + public function test_remove_end(): void + { + $start = new DateTimeImmutable("2021-01-01"); + $end = new DateTimeImmutable("2021-12-31"); + $date = Date::create($start, $end)->withoutEnd(); + + $this->assertNull($date->end()); + $this->assertFalse($date->isRange()); + } +}