start
This commit is contained in:
59
src/App/I18n.php
Normal file
59
src/App/I18n.php
Normal file
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App;
|
||||
|
||||
final class I18n
|
||||
{
|
||||
private array $current = [];
|
||||
private array $fallback = [];
|
||||
|
||||
public function __construct(private Config $config, private string $lang = 'en')
|
||||
{
|
||||
// Minimal example translations (normally load JSON/PHP arrays from disk)
|
||||
$this->fallback = [
|
||||
'common' => [
|
||||
'title' => 'Mini Example Landingpage',
|
||||
'intro' => 'This is a tiny project showing a clean bootstrap.',
|
||||
],
|
||||
'cta' => [
|
||||
'primary' => 'Continue',
|
||||
],
|
||||
];
|
||||
|
||||
$this->current = $this->fallback;
|
||||
}
|
||||
|
||||
private function traverse(array $data, string $key): mixed
|
||||
{
|
||||
$node = $data;
|
||||
foreach (explode('.', $key) as $seg) {
|
||||
if (!is_array($node) || !array_key_exists($seg, $node)) {
|
||||
return null;
|
||||
}
|
||||
$node = $node[$seg];
|
||||
}
|
||||
return $node;
|
||||
}
|
||||
|
||||
public function get(string $key, $default = '', array $vars = []): string
|
||||
{
|
||||
$val = $this->traverse($this->current, $key);
|
||||
if ($val === null) {
|
||||
$val = $this->traverse($this->fallback, $key);
|
||||
}
|
||||
if (!is_string($val)) {
|
||||
$val = (string)($default ?? '');
|
||||
}
|
||||
|
||||
// Built-ins
|
||||
$val = str_replace('{year}', date('Y'), $val);
|
||||
$val = str_replace('{{primary_url}}', $this->config->primaryUrl, $val);
|
||||
|
||||
foreach ($vars as $k => $v) {
|
||||
$val = str_replace('{' . $k . '}', (string)$v, $val);
|
||||
$val = str_replace('{{' . $k . '}}', (string)$v, $val);
|
||||
}
|
||||
return $val;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user