TemplateUpdater.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace App\Services;
  3. use App\Models\DistAppearancePublishList;
  4. use App\Models\SiteAppearanceTemplate;
  5. use Illuminate\Support\Facades\Storage;
  6. class TemplateUpdater
  7. {
  8. protected static ?string $baseTemplatePath = null;
  9. /**
  10. * 更新模板文件并更新数据库记录
  11. *
  12. * @param int $dist_id
  13. * @param int $appearance_id
  14. * @return string
  15. */
  16. public static function updateTemplates($dist): string
  17. {
  18. if(!$dist->appearance_id)
  19. {
  20. return "No appearance found for dist_id: $dist->id.";
  21. }
  22. // 使用默认值的函数封装,避免重复逻辑
  23. $template_dist_id = $dist->id ?? trim(config('liquid.template_dist_id'));
  24. $template_name = $dist->appearance->folder ?? trim(config('liquid.template_name'));
  25. if (self::$baseTemplatePath === null) {
  26. self::$baseTemplatePath = rtrim(config('liquid.template_path'), '/') . '/' .
  27. trim($template_dist_id). '/' .
  28. ltrim($template_name, '/');
  29. }
  30. // 查询 dist_appearance_publish_list 表的记录
  31. $publishList = DistAppearancePublishList::where('dist_id', $dist->id)
  32. ->where('appearance_id', $dist->appearance_id)
  33. ->first();
  34. if (!$publishList) {
  35. return "No publishList templates found in dist_appearance_template for dist_id: $dist?->id, appearance_id: $dist?->appearance_id.";
  36. }
  37. // 获取 template_update_code
  38. $updateCode = $publishList->template_update_code;
  39. // 查询 dist_appearance_template 表,获取与该 dist_id 和 appearance_id 对应的所有模板文件
  40. $templates = SiteAppearanceTemplate::where('dist_id', $dist->id)
  41. ->where('appearance_id', $dist->appearance_id)
  42. ->get();
  43. if ($templates->isEmpty()) {
  44. return "No templates found in dist_appearance_template for dist_id: $dist->id, appearance_id: $dist->appearance_id.";
  45. }
  46. // 循环处理每个模板文件
  47. foreach ($templates as $template) {
  48. // 如果文件名和路径不存在,生成默认值
  49. //$fileName = $template->file_name ?: "template_{$dist_id}_{$appearance_id}_{$template->id}.txt";
  50. $filePath = self::$baseTemplatePath.'/'.formatDirectory($template->file_path).$template->file_name;
  51. // 写入文件内容
  52. formatAndCreateAbsoluteDirectory($filePath);
  53. //// 强制转换内容为 UTF-8 编码
  54. $contentUtf8 = mb_convert_encoding($template->content, 'UTF-8', 'auto');
  55. // 写入文件内容,带 BOM
  56. file_put_contents($filePath, $contentUtf8);
  57. }
  58. // 更新 dist_appearance_publish_list 的 template_local_code
  59. $publishList->template_local_code = $updateCode;
  60. $publishList->save();
  61. return "Templates updated successfully for dist_id: $dist->id and appearance_id: $dist->appearance_id.";
  62. }
  63. }