|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Simples\Message; |
| 4 | + |
| 5 | +use Simples\Core\Helper\File; |
| 6 | +use Simples\Core\Kernel\App; |
| 7 | + |
| 8 | +/** |
| 9 | + * @method static string validation($i18, array $parameters = []) |
| 10 | + * @method static string auth($i18, array $parameters = []) |
| 11 | + * |
| 12 | + * Class Lang |
| 13 | + * @package Simples\Core\Kernel |
| 14 | + */ |
| 15 | +abstract class Lang |
| 16 | +{ |
| 17 | + /** |
| 18 | + * @param $default |
| 19 | + * @param string $fallback |
| 20 | + */ |
| 21 | + public static function locale($default, $fallback = '') |
| 22 | + { |
| 23 | + App::options('lang', ['default' => $default, 'fallback' => $fallback]); |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * @param $name |
| 28 | + * @param $arguments |
| 29 | + * @return string |
| 30 | + */ |
| 31 | + public static function __callStatic($name, $arguments) |
| 32 | + { |
| 33 | + if (isset($arguments[1])) { |
| 34 | + return self::lang($name, $arguments[0], $arguments[1]); |
| 35 | + } |
| 36 | + return self::lang($name, $arguments[0]); |
| 37 | + } |
| 38 | + |
| 39 | + |
| 40 | + /** |
| 41 | + * @param $scope |
| 42 | + * @param $path |
| 43 | + * @param array $parameters |
| 44 | + * @return string |
| 45 | + */ |
| 46 | + public static function lang($scope, $path, array $parameters = []) |
| 47 | + { |
| 48 | + $i18n = "Lang '{$scope}.{$path}' not found"; |
| 49 | + $languages = App::options('lang'); |
| 50 | + $filename = static::filename($scope, $languages['default'], $languages['fallback']); |
| 51 | + |
| 52 | + if ($filename) { |
| 53 | + /** @noinspection PhpIncludeInspection */ |
| 54 | + $phrases = include $filename; |
| 55 | + |
| 56 | + $i18n = search($phrases, $path); |
| 57 | + if (gettype($i18n) === TYPE_STRING) { |
| 58 | + return self::replace($i18n, $parameters); |
| 59 | + } |
| 60 | + } |
| 61 | + return $i18n; |
| 62 | + } |
| 63 | + |
| 64 | + /** |
| 65 | + * @param $i18n |
| 66 | + * @param $parameters |
| 67 | + * @return mixed |
| 68 | + */ |
| 69 | + public static function replace($i18n, $parameters) |
| 70 | + { |
| 71 | + foreach ($parameters as $key => $value) { |
| 72 | + $i18n = str_replace('{' . $key . '}', parse($value), $i18n); |
| 73 | + } |
| 74 | + return $i18n; |
| 75 | + } |
| 76 | + |
| 77 | + /** |
| 78 | + * @param string $scope |
| 79 | + * @param string $default |
| 80 | + * @param string $fallback |
| 81 | + * @return string |
| 82 | + */ |
| 83 | + private static function filename(string $scope, string $default, string $fallback): string |
| 84 | + { |
| 85 | + $filename = resources("locales/{$default}/{$scope}.php"); |
| 86 | + if (!File::exists($filename)) { |
| 87 | + $filename = resources("locales/{$fallback}/{$scope}.php"); |
| 88 | + } |
| 89 | + if (File::exists($filename)) { |
| 90 | + return $filename; |
| 91 | + } |
| 92 | + return ''; |
| 93 | + } |
| 94 | +} |
0 commit comments