From 76989ef19d6de33aeb682348de37a489a32d7635 Mon Sep 17 00:00:00 2001 From: KyleK Date: Wed, 19 Jun 2019 08:17:48 +0200 Subject: [PATCH] Fix #121 Allow custom format in asStructuredData() --- src/OpeningHours.php | 24 +++++++++++++----------- tests/OpeningHoursStructuredDataTest.php | 11 +++++++++++ 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/src/OpeningHours.php b/src/OpeningHours.php index b5b0797..3f055cb 100644 --- a/src/OpeningHours.php +++ b/src/OpeningHours.php @@ -521,35 +521,37 @@ public function flatMapExceptions(callable $callback): array return Arr::flatMap($this->exceptions, $callback); } - public function asStructuredData(): array + public function asStructuredData(string $format = 'H:i'): array { - $regularHours = $this->flatMap(function (OpeningHoursForDay $openingHoursForDay, string $day) { - return $openingHoursForDay->map(function (TimeRange $timeRange) use ($day) { + $regularHours = $this->flatMap(function (OpeningHoursForDay $openingHoursForDay, string $day) use ($format) { + return $openingHoursForDay->map(function (TimeRange $timeRange) use ($format, $day) { return [ '@type' => 'OpeningHoursSpecification', 'dayOfWeek' => ucfirst($day), - 'opens' => (string) $timeRange->start(), - 'closes' => (string) $timeRange->end(), + 'opens' => $timeRange->start()->format($format), + 'closes' => $timeRange->end()->format($format), ]; }); }); - $exceptions = $this->flatMapExceptions(function (OpeningHoursForDay $openingHoursForDay, string $date) { + $exceptions = $this->flatMapExceptions(function (OpeningHoursForDay $openingHoursForDay, string $date) use ($format) { if ($openingHoursForDay->isEmpty()) { + $zero = (new DateTime('2000-01-01 00:00:00'))->format($format); + return [[ '@type' => 'OpeningHoursSpecification', - 'opens' => '00:00', - 'closes' => '00:00', + 'opens' => $zero, + 'closes' => $zero, 'validFrom' => $date, 'validThrough' => $date, ]]; } - return $openingHoursForDay->map(function (TimeRange $timeRange) use ($date) { + return $openingHoursForDay->map(function (TimeRange $timeRange) use ($format, $date) { return [ '@type' => 'OpeningHoursSpecification', - 'opens' => (string) $timeRange->start(), - 'closes' => (string) $timeRange->end(), + 'opens' => $timeRange->start()->format($format), + 'closes' => $timeRange->end()->format($format), 'validFrom' => $date, 'validThrough' => $date, ]; diff --git a/tests/OpeningHoursStructuredDataTest.php b/tests/OpeningHoursStructuredDataTest.php index 05afa89..83457a2 100644 --- a/tests/OpeningHoursStructuredDataTest.php +++ b/tests/OpeningHoursStructuredDataTest.php @@ -64,5 +64,16 @@ public function it_can_render_opening_hours_as_an_array_of_structured_data() ]; $this->assertEquals($expected, $openingHours->asStructuredData()); + + $openingHours = OpeningHours::create([ + 'monday' => [ + 'hours' => [ + '09:00-17:00', + ], + ], + ]); + + $this->assertEquals('17:00:00+00:00', $openingHours->asStructuredData('H:i:sP')[0]['closes']); + } }