AppMessageTemplate.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. class AppMessageTemplate extends Model
  20. {
  21. /**
  22. * 数据表名称
  23. *
  24. * @var string
  25. */
  26. protected $table = 'app_message_templates';
  27. /**
  28. * 可批量赋值的属性
  29. *
  30. * @var array
  31. */
  32. protected $fillable = [
  33. 'name', // 模板名称
  34. 'code', // 模板代码
  35. 'type', // 消息类型
  36. 'title', // 消息标题模板
  37. 'content', // 消息内容模板
  38. 'variables', // 模板变量列表
  39. 'status' // 模板状态
  40. ];
  41. /**
  42. * 属性类型转换
  43. *
  44. * @var array
  45. */
  46. protected $casts = [
  47. 'variables' => 'array',
  48. 'type' => APP_MESSAGE_TYPE::class,
  49. 'status' => 'boolean'
  50. ];
  51. /**
  52. * 替换模板变量
  53. *
  54. * 使用提供的数据替换模板中的变量占位符
  55. * 变量格式为 {{变量名}}
  56. *
  57. * @param array $data 要替换的变量数据
  58. * @return array 替换后的标题和内容
  59. */
  60. public function replaceVariables(array $data): array
  61. {
  62. $title = $this->title;
  63. $content = $this->content;
  64. foreach ($data as $key => $value) {
  65. $title = str_replace('{{' . $key . '}}', $value, $title);
  66. $content = str_replace('{{' . $key . '}}', $value, $content);
  67. }
  68. return [
  69. 'title' => $title,
  70. 'content' => $content
  71. ];
  72. }
  73. }