ThemeController.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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' => [
  30. 'themes' => $themeConfigs,
  31. 'active' => config('v2board.theme', 'v2board')
  32. ]
  33. ]);
  34. }
  35. public function getThemeConfig(Request $request)
  36. {
  37. $payload = $request->validate([
  38. 'name' => 'required|in:' . join(',', $this->themes)
  39. ]);
  40. return response([
  41. 'data' => config("theme.{$payload['name']}")
  42. ]);
  43. }
  44. public function saveThemeConfig(Request $request)
  45. {
  46. $payload = $request->validate([
  47. 'name' => 'required|in:' . join(',', $this->themes),
  48. 'configs' => 'required|array'
  49. ]);
  50. $themeConfigFile = public_path("theme/{$payload['name']}/config.php");
  51. if (!File::exists($themeConfigFile)) abort(500, '主题不存在');
  52. $themeConfig = include($themeConfigFile);
  53. $validateFields = array_column($themeConfig['configs'], 'field_name');
  54. $config = [];
  55. foreach ($validateFields as $validateField) {
  56. if (!isset($payload['configs'][$validateField])) continue;
  57. $config[$validateField] = $payload['configs'][$validateField];
  58. }
  59. File::ensureDirectoryExists(base_path() . '/config/theme/');
  60. $data = var_export($config, 1);
  61. if (!File::put(base_path() . "/config/theme/{$payload['name']}.php", "<?php\n return $data ;")) {
  62. abort(500, '修改失败');
  63. }
  64. try {
  65. Artisan::call('config:cache');
  66. } catch (\Exception $e) {
  67. abort(500, '保存失败');
  68. }
  69. return response([
  70. 'data' => config('theme.v2board')
  71. ]);
  72. }
  73. }