TemplateUpdater.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Services;
  3. use App\Models\DistAppearancePublishList;
  4. use App\Models\DistAppearanceTemplate;
  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->title ?? 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. // 获取 template_update_code
  35. $updateCode = $publishList->template_update_code;
  36. // 查询 dist_appearance_template 表,获取与该 dist_id 和 appearance_id 对应的所有模板文件
  37. $templates = DistAppearanceTemplate::where('dist_id', $dist->id)
  38. ->where('appearance_id', $dist->appearance_id)
  39. ->get();
  40. if ($templates->isEmpty()) {
  41. return "No templates found in dist_appearance_template for dist_id: $dist->id, appearance_id: $dist->appearance_id.";
  42. }
  43. // 循环处理每个模板文件
  44. foreach ($templates as $template) {
  45. // 如果文件名和路径不存在,生成默认值
  46. //$fileName = $template->file_name ?: "template_{$dist_id}_{$appearance_id}_{$template->id}.txt";
  47. $filePath = self::$baseTemplatePath.'/'.formatDirectory($template->file_path).$template->file_name;
  48. // 写入文件内容
  49. formatAndCreateAbsoluteDirectory($filePath);
  50. //// 强制转换内容为 UTF-8 编码
  51. $contentUtf8 = mb_convert_encoding($template->content, 'UTF-8', 'auto');
  52. // 写入文件内容,带 BOM
  53. file_put_contents($filePath, $contentUtf8);
  54. }
  55. // 更新 dist_appearance_publish_list 的 template_local_code
  56. $publishList->template_local_code = $updateCode;
  57. $publishList->save();
  58. return "Templates updated successfully for dist_id: $dist->id and appearance_id: $dist->appearance_id.";
  59. }
  60. }