HasStateText.php 647 B

12345678910111213141516171819202122232425262728293031323334
  1. <?php
  2. declare(encoding='UTF-8');
  3. namespace App\Traits;
  4. /**
  5. * 状态文本转换 Trait
  6. */
  7. trait HasStateText
  8. {
  9. /**
  10. * 获取状态文本
  11. */
  12. public function getStateTextAttribute(): string
  13. {
  14. if (! isset($this->stateEnumClass)) {
  15. return '未知状态';
  16. }
  17. $enumClass = $this->stateEnumClass;
  18. return $enumClass::fromValue($this->state)?->label() ?? '未知状态';
  19. }
  20. /**
  21. * 初始化 HasStateText trait
  22. */
  23. public function initializeHasStateText(): void
  24. {
  25. // 自动添加 state_text 到 appends 数组
  26. $this->append('state_text');
  27. }
  28. }