| 1 |
<?php |
| 2 |
|
| 3 |
namespace App\Billingo\Service; |
| 4 |
|
| 5 |
class BillingoTranslator |
| 6 |
{ |
| 7 |
protected $translator = []; |
| 8 |
private static ?BillingoTranslator $instance = null; |
| 9 |
|
| 10 |
private function __construct(?string $locale) |
| 11 |
{ |
| 12 |
if (is_null($locale)) { |
| 13 |
$config = require __DIR__ . '/../config.php'; |
| 14 |
$locale = $config['local']; |
| 15 |
} |
| 16 |
|
| 17 |
$this->loadTranslations($locale); |
| 18 |
} |
| 19 |
|
| 20 |
private function loadTranslations(string $locale): void |
| 21 |
{ |
| 22 |
$langPath = __DIR__ . '/../Lang/' . $locale; |
| 23 |
|
| 24 |
if (!is_dir($langPath)) { |
| 25 |
return; |
| 26 |
} |
| 27 |
|
| 28 |
$files = glob($langPath . '/*.php'); |
| 29 |
|
| 30 |
foreach ($files as $file) { |
| 31 |
$group = basename($file, '.php'); |
| 32 |
$this->translator[$group] = require $file; |
| 33 |
} |
| 34 |
} |
| 35 |
|
| 36 |
public static function getInstance(?string $locale = null): BillingoTranslator |
| 37 |
{ |
| 38 |
if (self::$instance == null) { |
| 39 |
self::$instance = new BillingoTranslator($locale); |
| 40 |
} |
| 41 |
|
| 42 |
return self::$instance; |
| 43 |
} |
| 44 |
|
| 45 |
public function translate($key): string |
| 46 |
{ |
| 47 |
$segments = explode('.', $key); |
| 48 |
|
| 49 |
if (count($segments) < 2) { |
| 50 |
return $key; |
| 51 |
} |
| 52 |
|
| 53 |
$group = $segments[0]; |
| 54 |
$item = $segments[1]; |
| 55 |
|
| 56 |
if (!isset($this->translator[$group]) || !isset($this->translator[$group][$item])) { |
| 57 |
return $key; |
| 58 |
} |
| 59 |
|
| 60 |
return $this->translator[$group][$item]; |
| 61 |
} |
| 62 |
} |
| 63 |
|