AppMessageTemplate.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace App\Module\Ulogic\Models;
  3. use App\Module\AppMessage\Enums\APP_MESSAGE_TYPE;
  4. use Illuminate\Database\Eloquent\Model;
  5. /**
  6. * 应用消息模板模型
  7. *
  8. * @property int $id 模板ID
  9. * @property string $name 模板名称
  10. * @property string $code 模板代码
  11. * @property string $type 消息类型
  12. * @property string $title 消息标题模板
  13. * @property string $content 消息内容模板
  14. * @property array $variables 模板变量列表
  15. * @property bool $status 模板状态
  16. * @property \Carbon\Carbon $created_at 创建时间
  17. * @property \Carbon\Carbon $updated_at 更新时间
  18. */
  19. /**
  20. * App\Module\Ulogic\Models\AppMessageTemplate
  21. *
  22. * field start
  23. * @property int $id
  24. * @property string $name 模板名称
  25. * @property string $code 模板代码
  26. * @property string $type 消息类型:system=系统消息,user=用户消息
  27. * @property string $title 消息标题
  28. * @property string $content 消息内容
  29. * @property string $content_type 内容类型:text=纯文本,html=富文本,markdown=MD格式,json=JSON格式
  30. * @property object|array $variables 变量定义
  31. * @property int $allow_reply 是否允许回复:0不允许 1允许
  32. * @property int $status 状态:0禁用 1启用
  33. * @property \Carbon\Carbon $created_at 创建时间
  34. * @property \Carbon\Carbon $updated_at 更新时间
  35. * field end
  36. */
  37. class AppMessageTemplate extends Model
  38. {
  39. /**
  40. * 数据表名称
  41. *
  42. * @var string
  43. */
  44. protected $table = 'app_message_templates';
  45. // attrlist start
  46. protected $fillable = [
  47. 'id',
  48. 'name',
  49. 'code',
  50. 'type',
  51. 'title',
  52. 'content',
  53. 'content_type',
  54. 'variables',
  55. 'allow_reply',
  56. 'status',
  57. ];
  58. // attrlist end
  59. /**
  60. * 属性类型转换
  61. *
  62. * @var array
  63. */
  64. protected $casts = [
  65. 'variables' => 'array',
  66. 'type' => APP_MESSAGE_TYPE::class,
  67. 'status' => 'boolean'
  68. ];
  69. /**
  70. * 替换模板变量
  71. *
  72. * 使用提供的数据替换模板中的变量占位符
  73. * 变量格式为 {{变量名}}
  74. *
  75. * @param array $data 要替换的变量数据
  76. * @return array 替换后的标题和内容
  77. */
  78. public function replaceVariables(array $data): array
  79. {
  80. $title = $this->title;
  81. $content = $this->content;
  82. foreach ($data as $key => $value) {
  83. $title = str_replace('{{' . $key . '}}', $value, $title);
  84. $content = str_replace('{{' . $key . '}}', $value, $content);
  85. }
  86. return [
  87. 'title' => $title,
  88. 'content' => $content
  89. ];
  90. }
  91. }