Translator.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace Dcat\Admin\Support;
  3. class Translator
  4. {
  5. protected static $method;
  6. /**
  7. * @var \Illuminate\Contracts\Translation\Translator
  8. */
  9. protected $translator;
  10. /**
  11. * @var string
  12. */
  13. protected $path;
  14. public function __construct()
  15. {
  16. $this->translator = app('translator');
  17. $this->path = admin_controller_slug();
  18. }
  19. /**
  20. * 设置翻译文件路径.
  21. *
  22. * @param null|string $path
  23. *
  24. * @return void
  25. */
  26. public function setPath(?string $path)
  27. {
  28. $this->path = $path;
  29. }
  30. /**
  31. * 翻译字段名称.
  32. *
  33. * @param string $field
  34. * @param null $locale
  35. *
  36. * @return false|mixed|string|string[]
  37. */
  38. public function transField(?string $field, $locale = null)
  39. {
  40. return $this->trans("{$this->path}.fields.{$field}", [], $locale);
  41. }
  42. /**
  43. * 翻译Label.
  44. *
  45. * @param null|string $label
  46. * @param array $replace
  47. * @param string $locale
  48. *
  49. * @return array|\Illuminate\Contracts\Translation\Translator|string|null
  50. */
  51. public function transLabel(?string $label = null, $replace = [], $locale = null)
  52. {
  53. $label = $label ?: admin_controller_name();
  54. return $this->trans("{$this->path}.labels.{$label}", $replace, $locale);
  55. }
  56. /**
  57. * 翻译.
  58. *
  59. * @param string $key
  60. * @param array $replace
  61. * @param string $locale
  62. *
  63. * @return false|mixed|string|string[]
  64. */
  65. public function trans($key, array $replace = [], $locale = null)
  66. {
  67. $method = $this->getTranslateMethod();
  68. if ($this->translator->has($key)) {
  69. return $this->translator->$method($key, $replace, $locale);
  70. }
  71. if (
  72. mb_strpos($key, 'global.') !== 0
  73. && count($arr = explode('.', $key)) > 1
  74. ) {
  75. unset($arr[0]);
  76. array_unshift($arr, 'global');
  77. $key = implode('.', $arr);
  78. if (! $this->translator->has($key)) {
  79. return end($arr);
  80. }
  81. return $this->translator->$method($key, $replace, $locale);
  82. }
  83. return last(explode('.', $key));
  84. }
  85. protected function getTranslateMethod()
  86. {
  87. if (static::$method === null) {
  88. static::$method = version_compare(app()->version(), '6.0', '>=') ? 'get' : 'trans';
  89. }
  90. return static::$method;
  91. }
  92. }