diff --git a/src/LocalizedStrftimeFormatter.php b/src/LocalizedStrftimeFormatter.php index 4e0f5e6..1cd61cc 100644 --- a/src/LocalizedStrftimeFormatter.php +++ b/src/LocalizedStrftimeFormatter.php @@ -152,24 +152,18 @@ private function strftime(string $format, DateTimeImmutable $timestamp, string $ $replace = $translationTable[$pattern]; - if (is_callable($replace)) { - $result = $replace($timestamp, $pattern); - } - else { + if (is_string($replace)) { $result = $timestamp->format($replace); } - - switch ($prefix) { - case '_': - // replace leading zeros with spaces but keep last char if also zero - return preg_replace('/\G0(?=.)/', ' ', $result); - case '#': - case '-': - // remove leading zeros but keep last char if also zero - return preg_replace('/^0+(?=.)/', '', $result); + else { + $result = $replace($timestamp, $pattern); } - return $result; + return match ($prefix) { + '_' => (string)preg_replace('/\G0(?=.)/', ' ', $result), + '#', '-' => (string)preg_replace('/^0+(?=.)/', '', $result), + default => $result, + }; }, $format); return str_replace('%%', '%', $out); diff --git a/tests/LocalizedStrftimeFormatterTest.php b/tests/LocalizedStrftimeFormatterTest.php new file mode 100644 index 0000000..3b980fc --- /dev/null +++ b/tests/LocalizedStrftimeFormatterTest.php @@ -0,0 +1,38 @@ +assertSame('mánudagur 21. ágúst 2023 kl. 16:26 Test', $formatter->format($date)); + } + + public function testEnglishFormat(): void + { + $formatter = new LocalizedStrftimeFormatter('en_GB', '%A %c Test'); + + $date = new DateTimeImmutable('2023-08-21 16:26:14'); + + $this->assertSame('Monday 21 August 2023 at 16:26 Test', $formatter->format($date)); + } + + public function testGlobalFunctionCalls(): void + { + $formatter = new LocalizedStrftimeFormatter('is_IS', '%Y'); + + $date = new DateTimeImmutable('2023-08-21 16:26:14'); + + $this->assertSame('2023', $formatter->format($date)); + } +} + +function Y() { + throw new \RuntimeException('Should not be called'); +}