LangCreator.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace Dcat\Admin\Scaffold;
  3. use Dcat\Admin\Support\Helper;
  4. use Illuminate\Support\Facades\App;
  5. class LangCreator
  6. {
  7. protected $fields = [];
  8. public function __construct(array $fields)
  9. {
  10. $this->fields = $fields;
  11. }
  12. /**
  13. * 生成语言包.
  14. *
  15. * @param string $controller
  16. * @param string $title
  17. *
  18. * @return string
  19. */
  20. public function create(string $controller, ?string $title)
  21. {
  22. $controller = str_replace('Controller', '', class_basename($controller));
  23. $filename = $this->getLangPath($controller);
  24. if (is_file($filename)) {
  25. return;
  26. }
  27. $title = $title ?: $controller;
  28. $content = [
  29. 'labels' => [
  30. $controller => $title,
  31. Helper::slug($controller) => $title,
  32. ],
  33. 'fields' => [],
  34. 'options' => [],
  35. ];
  36. foreach ($this->fields as $field) {
  37. if (empty($field['name'])) {
  38. continue;
  39. }
  40. $content['fields'][$field['name']] = $field['translation'] ?: $field['name'];
  41. }
  42. $files = app('files');
  43. if ($files->put($filename, Helper::exportArrayPhp($content))) {
  44. $files->chmod($filename, 0777);
  45. return $filename;
  46. }
  47. }
  48. /**
  49. * 获取语言包路径.
  50. *
  51. * @param string $controller
  52. *
  53. * @return string
  54. */
  55. protected function getLangPath(string $controller)
  56. {
  57. $path = resource_path('lang/'.App::getLocale());
  58. return $path.'/'.Helper::slug($controller).'.php';
  59. }
  60. }