PreviewTemplateUpdater.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Services;
  3. use App\Models\DistAppearancePublishList;
  4. use App\Models\DistAppearanceTemplate;
  5. class PreviewTemplateUpdater
  6. {
  7. protected static ?string $baseTemplatePath = null;
  8. /**
  9. * 预览更新模板文件并更新数据库记录
  10. *
  11. * @param int $dist_id
  12. * @param int $appearance_id
  13. * @return string
  14. */
  15. public static function updateTemplates($dist): string
  16. {
  17. if(!$dist->appearance_id)
  18. {
  19. return "No appearance found for dist_id: $dist->id.";
  20. }
  21. // 使用默认值的函数封装,避免重复逻辑
  22. $template_dist_id = $dist->id ?? trim(config('liquid.template_dist_id'));
  23. $template_name = $dist->appearance->folder;
  24. if (self::$baseTemplatePath === null) {
  25. self::$baseTemplatePath = rtrim(config('liquid.preview_template_path'), '/') . '/' .
  26. trim($template_dist_id). '/' .
  27. ltrim($template_name, '/');
  28. }
  29. // 查询 dist_appearance_template 表,获取与该 dist_id 和 appearance_id 对应的所有模板文件
  30. $templates = DistAppearanceTemplate::where('dist_id', $dist->id)
  31. ->where('appearance_id', $dist->appearance_id)
  32. ->get();
  33. if ($templates->isEmpty()) {
  34. return "No templates found in dist_appearance_template for dist_id: $dist->id, appearance_id: $dist->appearance_id.";
  35. }
  36. // 循环处理每个模板文件
  37. foreach ($templates as $template) {
  38. $content = self::contentChange($template->content,$template->template_code);
  39. // 如果文件名和路径不存在,生成默认值
  40. //$fileName = $template->file_name ?: "template_{$dist_id}_{$appearance_id}_{$template->id}.txt";
  41. $filePath = self::$baseTemplatePath.'/'.formatDirectory($template->file_path).$template->file_name;
  42. // 写入文件内容
  43. formatAndCreateAbsoluteDirectory($filePath);
  44. //// 强制转换内容为 UTF-8 编码
  45. $contentUtf8 = mb_convert_encoding($content, 'UTF-8', 'auto');
  46. // 写入文件内容,带 BOM
  47. file_put_contents($filePath, $contentUtf8);
  48. }
  49. return "";
  50. }
  51. /*
  52. * TODO: 模板内容增加 mtb_id 属性,用于区分不同模板
  53. */
  54. public static function contentChange($content,$templateCode)
  55. {
  56. $count = 1;
  57. $newContent = preg_replace_callback(
  58. '/(<[^>]+?mtb_edit=[\'"][^\'"]+[\'"][^>]*>)/',
  59. function ($matches) use (&$count, $templateCode) {
  60. // 在匹配到的 HTML 元素后添加 mtb_id 属性
  61. return preg_replace('/(mtb_edit=[\'"][^\'"]+[\'"])([^>]*)>/', '$1 mtb_id="' . $templateCode .'_'. $count++ . '"$2>', $matches[0]);
  62. },
  63. $content
  64. );
  65. return $newContent;
  66. }
  67. }