ThemeController.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Http\Controllers\Admin;
  3. use App\Http\Controllers\Controller;
  4. use Illuminate\Support\Facades\File;
  5. use Illuminate\Support\Facades\Artisan;
  6. use Illuminate\Http\Request;
  7. class ThemeController extends Controller
  8. {
  9. private $themes;
  10. private $path;
  11. public function __construct()
  12. {
  13. $this->path = $path = public_path('theme/');
  14. $this->themes = array_map(function ($item) use ($path) {
  15. return str_replace($path, '', $item);
  16. }, glob($path . '*'));
  17. }
  18. public function getThemes()
  19. {
  20. $themeConfigs = [];
  21. foreach ($this->themes as $theme) {
  22. $themeConfigFile = $this->path . "{$theme}/config.php";
  23. if (!File::exists($themeConfigFile)) continue;
  24. $themeConfig = include($themeConfigFile);
  25. if (!isset($themeConfig['configs']) || !is_array($themeConfig)) continue;
  26. $themeConfigs[$this->themes] = $themeConfig;
  27. }
  28. return response([
  29. 'data' => $themeConfigs
  30. ]);
  31. }
  32. public function getThemeConfig(Request $request)
  33. {
  34. return response([
  35. 'data' => config('theme.v2board')
  36. ]);
  37. }
  38. public function saveThemeConfig(Request $request)
  39. {
  40. $payload = $request->validate([
  41. 'name' => 'required|in:' . join(',', $this->themes),
  42. 'configs' => 'required|array'
  43. ]);
  44. $themeConfigFile = public_path("theme/{$payload['name']}/config.php");
  45. if (!File::exists($themeConfigFile)) abort(500, '主题不存在');
  46. $themeConfig = include($themeConfigFile);
  47. $validateFields = array_column($themeConfig['configs'], 'field_name');
  48. $config = [];
  49. foreach ($validateFields as $validateField) {
  50. if (!isset($payload['configs'][$validateField])) continue;
  51. $config[$validateField] = $payload['configs'][$validateField];
  52. }
  53. File::ensureDirectoryExists(base_path() . '/config/theme/');
  54. $data = var_export($config, 1);
  55. if (!File::put(base_path() . "/config/theme/{$payload['name']}.php", "<?php\n return $data ;")) {
  56. abort(500, '修改失败');
  57. }
  58. try {
  59. Artisan::call('config:cache');
  60. } catch (\Exception $e) {
  61. abort(500, '保存失败');
  62. }
  63. return response([
  64. 'data' => config('theme.v2board')
  65. ]);
  66. }
  67. }