RecentResource.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Http\Resources;
  3. use App\Http\Api\ChannelApi;
  4. use App\Models\Article;
  5. use App\Models\DhammaTerm;
  6. use App\Models\Sentence;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Http\Resources\Json\JsonResource;
  9. class RecentResource extends JsonResource
  10. {
  11. /**
  12. * Transform the resource into an array.
  13. *
  14. * id 是 uuid、type 是 article/chapter/term 之一、article_id 是
  15. * `"{book}-{para}"` 之类的字符串(不是数字)。
  16. *
  17. * @param Request $request
  18. * @return array{
  19. * id: string,
  20. * type: string,
  21. * article_id: string,
  22. * param: string|null,
  23. * updated_at: string,
  24. * title: string
  25. * }
  26. */
  27. public function toArray($request)
  28. {
  29. $data = [
  30. 'id' => $this->id,
  31. 'type' => $this->type,
  32. 'article_id' => $this->article_id,
  33. 'param' => $this->param,
  34. 'updated_at' => $this->updated_at,
  35. ];
  36. $title = '';
  37. switch ($this->type) {
  38. case 'article':
  39. $title = Article::where('uid', $this->article_id)->value('title');
  40. break;
  41. case 'chapter':
  42. if (! empty($this->param)) {
  43. $param = json_decode($this->param, true);
  44. if (isset($param['channel'])) {
  45. $channelId = explode('_', $param['channel'])[0];
  46. }
  47. }
  48. $paliChannel = ChannelApi::getSysChannel('_System_Pali_VRI_');
  49. if (! isset($channelId)) {
  50. $channelId = $paliChannel;
  51. }
  52. $para = explode('-', $this->article_id);
  53. if (count($para) === 2) {
  54. $title = Sentence::where('book_id', (int) $para[0])
  55. ->where('paragraph', (int) $para[1])
  56. ->where('channel_uid', $channelId)
  57. ->value('content');
  58. if (empty($title)) {
  59. $title = Sentence::where('book_id', (int) $para[0])
  60. ->where('paragraph', (int) $para[1])
  61. ->where('channel_uid', $paliChannel)
  62. ->value('content');
  63. }
  64. }
  65. break;
  66. case 'term':
  67. $title = DhammaTerm::where('guid', $this->article_id)->value('word');
  68. break;
  69. default:
  70. $title = $this->article_id;
  71. break;
  72. }
  73. $data['title'] = $title;
  74. return $data;
  75. }
  76. }