ThemeService.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Artisan;
  4. use Illuminate\Support\Facades\File;
  5. class ThemeService
  6. {
  7. private $path;
  8. private $theme;
  9. public function __construct($theme)
  10. {
  11. $this->theme = $theme;
  12. $this->path = $path = public_path('theme/');
  13. }
  14. public function init()
  15. {
  16. $themeConfigFile = $this->path . "{$this->theme}/config.json";
  17. if (!File::exists($themeConfigFile)) abort(500, "{$this->theme}主题不存在");
  18. $themeConfig = json_decode(File::get($themeConfigFile), true);
  19. if (!isset($themeConfig['configs']) || !is_array($themeConfig)) abort(500, "{$this->theme}主题配置文件有误");
  20. $configs = $themeConfig['configs'];
  21. $data = [];
  22. foreach ($configs as $config) {
  23. $data[$config['field_name']] = isset($config['default_value']) ? $config['default_value'] : '';
  24. }
  25. $data = var_export($data, 1);
  26. try {
  27. if (!File::put(base_path() . "/config/theme/{$this->theme}.php", "<?php\n return $data ;")) {
  28. abort(500, "{$this->theme}初始化失败");
  29. }
  30. } catch (\Exception $e) {
  31. abort(500, '请检查V2Board目录权限');
  32. }
  33. try {
  34. Artisan::call('config:cache');
  35. while (true) {
  36. if (config("theme.{$this->theme}")) break;
  37. }
  38. } catch (\Exception $e) {
  39. abort(500, "{$this->theme}初始化失败");
  40. }
  41. }
  42. }