Skip to content

Commit ceb1c6f

Browse files
committedSep 19, 2024
Add langParam method
1 parent a09e609 commit ceb1c6f

File tree

4 files changed

+32
-4
lines changed

4 files changed

+32
-4
lines changed
 

‎example.php

+11-1
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,22 @@
2121
)
2222
);
2323

24+
// Get current date
25+
$currentDate = new DateTime();
26+
$year = $currentDate->format('Y'); // YYYY
27+
$month = $currentDate->format('m'); // MM
28+
$day = $currentDate->format('d'); // dd
29+
30+
// Example usage
31+
$params = [$year, $month, $day];
32+
2433
try {
2534
$i18n = new I18n($config);
2635
$i18n->setLangAlias(array('en_US' => 'English', 'zh_TW' => '繁體中文'));
2736
echo '<h2>Fetch \'hello\' from \'greeting.json\'</h2>';
2837
echo $i18n->fetch('greeting.hello');
29-
echo $i18n->fetch('greeting.world');
38+
echo $i18n->fetch('greeting.world').'<br>';
39+
echo $i18n->fetch('general.today', $params);
3040
echo '<h2>Fetch Current Language</h2>';
3141
echo $i18n->fetchCurrentLang();
3242
echo '<h2>Fetch List</h2>';

‎lang/en_US/general.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
{
2-
"welcome_message": "Welcome to I18n!"
2+
"welcome_message": "Welcome to I18n!",
3+
"today": "Today is {0}/{1}/{2}"
34
}

‎lang/zh_TW/general.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
{
2-
"welcome_message": "歡迎使用I18n!"
2+
"welcome_message": "歡迎使用I18n!",
3+
"today": "今天是{0}/{1}/{2}"
34
}

‎src/I18n.php

+17-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ public function getLangAlias(): array
7474
return $this->fetchLangList();
7575
}
7676

77-
public function fetch(string $key): ?string
77+
public function fetch(string $key, ?array $param = null): ?string
7878
{
7979
if (!$this->initialized) {
8080
throw new InitializationException('I18n class must be initialized before using fetch().');
@@ -86,6 +86,10 @@ public function fetch(string $key): ?string
8686
$value = $this->languageLoader->getValue(self::$option['defaultLang'], $key);
8787
}
8888

89+
if ($param !== null) {
90+
$value = self::langParam($value, $param);
91+
}
92+
8993
return $value;
9094
}
9195

@@ -116,6 +120,18 @@ public function fetchCurrentLang(): string
116120
return $this->currentLang;
117121
}
118122

123+
public static function langParam(string $value, array $param): string
124+
{
125+
$replacements = [];
126+
127+
// Construct replacement array
128+
foreach ($param as $index => $p) {
129+
$replacements['{' . $index . '}'] = $p; // Placeholder as key
130+
}
131+
132+
return strtr($value, $replacements);
133+
}
134+
119135
private function validateLanguageFolder(string $folder): string
120136
{
121137
$folderPath = self::$option['langFilePath'].Utils::DIR_SEP.$folder;

0 commit comments

Comments
 (0)
Please sign in to comment.