Skip to content

Commit

Permalink
Fix #121 Allow custom format in asStructuredData()
Browse files Browse the repository at this point in the history
  • Loading branch information
kylekatarnls committed Jun 19, 2019
1 parent d497ef6 commit 76989ef
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 11 deletions.
24 changes: 13 additions & 11 deletions src/OpeningHours.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
];
Expand Down
11 changes: 11 additions & 0 deletions tests/OpeningHoursStructuredDataTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']);

}
}

0 comments on commit 76989ef

Please sign in to comment.