GettextServiceProvider.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace App\Providers {
  3. use App\Gettext\Gettext;
  4. use Illuminate\Support\ServiceProvider;
  5. class GettextServiceProvider extends ServiceProvider
  6. {
  7. /**
  8. * Register services.
  9. *
  10. * @return void
  11. */
  12. public function register()
  13. {
  14. return $this->load(config('gettext'));
  15. }
  16. /**
  17. * Bootstrap services.
  18. *
  19. * @return void
  20. */
  21. public function boot()
  22. {
  23. //
  24. }
  25. public function load(array $config)
  26. {
  27. if (empty($config)) {
  28. return;
  29. }
  30. $config['storage'] = base_path($config['storage']);
  31. foreach ($config['directories'] as $key => $directory) {
  32. $config['directories'][$key] = base_path($directory);
  33. }
  34. $gettext = new Gettext($config);
  35. $this->app->singleton('gettext', function () use ($gettext) {
  36. return $gettext;
  37. });
  38. return $gettext;
  39. }
  40. /**
  41. * Get the services provided by the provider.
  42. *
  43. * @return array
  44. */
  45. public function provides()
  46. {
  47. return ['gettext'];
  48. }
  49. }
  50. }
  51. namespace {
  52. function _e($original)
  53. {
  54. static $translator;
  55. $countryCode = collect(config('constants.countries'))->filter(function ($country) {
  56. return \Str::contains($country, session('locale'));
  57. })->first();
  58. if (session('user.is_member')) {
  59. app('gettext')->setLocale(config('constants.countries')[0], session('user.CountryCode'));
  60. } else if (session('member.is_member')) {
  61. app('gettext')->setLocale(config('constants.countries')[0], $countryCode);
  62. } else {
  63. app('gettext')->setLocale(config('constants.countries')[0], session('user.CountryCode') ?? $countryCode);
  64. }
  65. app('gettext')->load();
  66. if (empty($translator)) {
  67. $translator = app('gettext')->getTranslator();
  68. }
  69. $text = $translator->gettext($original);
  70. if (func_num_args() === 1) {
  71. return $text;
  72. }
  73. $args = array_slice(func_get_args(), 1);
  74. return is_array($args[0]) ? strtr($text, $args[0]) : vsprintf($text, $args);
  75. }
  76. }