Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 8 additions & 14 deletions src/LocalizedStrftimeFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
38 changes: 38 additions & 0 deletions tests/LocalizedStrftimeFormatterTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php declare(strict_types=1);

use PHPUnit\Framework\TestCase;
use Sunkan\Dictus\LocalizedStrftimeFormatter;

final class LocalizedStrftimeFormatterTest extends TestCase
{
public function testReadableFormat(): void
{
$formatter = new LocalizedStrftimeFormatter('is_IS', '%A %c Test');

$date = new DateTimeImmutable('2023-08-21 16:26:14');

$this->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');
}