Skip to content

Commit

Permalink
added filters |localDate & |localTime WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Nov 20, 2023
1 parent b7128c6 commit f27bac1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
2 changes: 2 additions & 0 deletions src/Latte/Essential/CoreExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,8 @@ public function getFilters(): array
'webalize' => class_exists(Nette\Utils\Strings::class)
? [Nette\Utils\Strings::class, 'webalize']
: function () { throw new RuntimeException('Filter |webalize requires nette/utils package.'); },
'localDate' => fn($date, string $format = 'medium') => Filters::localDateTime($date, $format, true),
'localTime' => fn($time, string $format = 'medium') => Filters::localDateTime($time, $format, false),
];
}

Expand Down
35 changes: 28 additions & 7 deletions src/Latte/Essential/Filters.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,17 +172,12 @@ public static function date(string|int|\DateTimeInterface|\DateInterval|null $ti
return null;
}

if (!isset($format)) {
$format = Latte\Runtime\Filters::$dateFormat;
}

$format ??= Latte\Runtime\Filters::$dateFormat;
if ($time instanceof \DateInterval) {
return $time->format($format);

} elseif (is_numeric($time)) {
$time = new \DateTime('@' . $time);
$time->setTimeZone(new \DateTimeZone(date_default_timezone_get()));

$time = (new \DateTime)->setTimestamp((int) $time);
} elseif (!$time instanceof \DateTimeInterface) {
$time = new \DateTime($time);
}
Expand All @@ -199,6 +194,32 @@ public static function date(string|int|\DateTimeInterface|\DateInterval|null $ti
}


/**
* Local date/time formatting.
*/
public static function localDateTime(string|int|\DateTimeInterface|null $time, string $format, bool $date): ?string
{
if (!class_exists(\IntlDateFormatter::class)) {
throw new Latte\RuntimeException("Filters |localDate and |localTime requires 'intl' extension.");
} elseif ($time == null) { // intentionally ==
return null;
} elseif (is_numeric($time)) {
$time = (new \DateTime)->setTimestamp((int) $time);
} elseif (is_string($time)) {
$time = new \DateTime($time);
}

$format = match ($format) {
'short' => \IntlDateFormatter::SHORT,
'medium' => \IntlDateFormatter::MEDIUM,
'long' => \IntlDateFormatter::LONG,
'full' => \IntlDateFormatter::FULL,
default => throw new Latte\RuntimeException("Unknown format '$format' used in |localDate or |localTime."),
};
return \IntlDateFormatter::formatObject($time, $date ? [$format, \IntlDateFormatter::NONE] : [\IntlDateFormatter::NONE, $format]);
}


/**
* Converts to human readable file size.
*/
Expand Down

0 comments on commit f27bac1

Please sign in to comment.