AppMessageTemplate.php 2.2 KB

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