View.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Services;
  4. use App\Models\Config;
  5. use Illuminate\Database\DatabaseManager;
  6. use Smarty\Smarty;
  7. use Twig\Environment;
  8. use Twig\Loader\FilesystemLoader;
  9. use const BASE_PATH;
  10. final class View
  11. {
  12. public static DatabaseManager $connection;
  13. public static float $beginTime;
  14. public static function getSmarty(): Smarty
  15. {
  16. $smarty = new Smarty(); //实例化smarty
  17. $user = Auth::getUser();
  18. $smarty->setTemplateDir(BASE_PATH . '/resources/views/' . self::getTheme($user) . '/'); //设置模板文件存放目录
  19. $smarty->setCompileDir(BASE_PATH . '/storage/framework/smarty/compile/'); //设置生成文件存放目录
  20. $smarty->setCacheDir(BASE_PATH . '/storage/framework/smarty/cache/'); //设置缓存文件存放目录
  21. // add config
  22. $smarty->assign('config', self::getConfig());
  23. $smarty->assign('public_setting', Config::getPublicConfig());
  24. $smarty->assign('user', $user);
  25. return $smarty;
  26. }
  27. public static function getTwig(): Environment
  28. {
  29. $loader = new FilesystemLoader(BASE_PATH . '/resources/views/' . self::getTheme($user) . '/');
  30. $twig = new Environment($loader, [
  31. 'cache' => BASE_PATH . '/storage/framework/twig/cache/',
  32. ]);
  33. $twig->addGlobal('config', self::getConfig());
  34. $twig->addGlobal('public_setting', Config::getPublicConfig());
  35. $twig->addGlobal('user', $user);
  36. return $twig;
  37. }
  38. public static function getTheme($user): string
  39. {
  40. if ($user->isLogin) {
  41. $theme = $user->theme;
  42. } else {
  43. $theme = $_ENV['theme'];
  44. }
  45. return $theme;
  46. }
  47. public static function getConfig(): array
  48. {
  49. return [
  50. 'appName' => $_ENV['appName'],
  51. 'baseUrl' => $_ENV['baseUrl'],
  52. 'jump_delay' => $_ENV['jump_delay'],
  53. 'enable_kill' => $_ENV['enable_kill'],
  54. 'enable_change_email' => $_ENV['enable_change_email'],
  55. 'enable_r2_client_download' => $_ENV['enable_r2_client_download'],
  56. 'jsdelivr_url' => $_ENV['jsdelivr_url'],
  57. ];
  58. }
  59. }