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 af9cf23 commit e459b75
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 @@ -141,6 +141,8 @@ public function getFilters(): array
'join' => [Filters::class, 'implode'],
'last' => [Filters::class, 'last'],
'length' => [Filters::class, 'length'],
'localDate' => fn($date, string $format = 'medium') => Filters::localDateTime($date, $format, date: true),
'localTime' => fn($time, string $format = 'medium') => Filters::localDateTime($time, $format, date: false),
'lower' => extension_loaded('mbstring')
? [Filters::class, 'lower']
: function () { throw new RuntimeException('Filter |lower requires mbstring extension.'); },
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 e459b75

Please sign in to comment.