DiscussionResource.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Http\Resources;
  3. use App\Http\Api\MdRender;
  4. use App\Http\Api\UserApi;
  5. use App\Models\Discussion;
  6. use App\Models\Sentence;
  7. use Illuminate\Contracts\Support\Arrayable;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Http\Resources\Json\JsonResource;
  10. use Illuminate\Support\Str;
  11. class DiscussionResource extends JsonResource
  12. {
  13. /**
  14. * Transform the resource into an array.
  15. *
  16. * @param Request $request
  17. * @return array|Arrayable|\JsonSerializable
  18. */
  19. public function toArray($request)
  20. {
  21. $data = [
  22. 'id' => $this->id,
  23. 'title' => $this->title,
  24. 'content' => $this->content,
  25. 'content_type' => $this->content_type,
  26. 'parent' => $this->parent,
  27. 'status' => $this->status,
  28. 'editor' => UserApi::getByUuid($this->editor_uid),
  29. 'res_id' => $this->res_id,
  30. 'res_type' => $this->res_type,
  31. 'type' => $this->type,
  32. 'tpl_id' => $this->tpl_id,
  33. 'children_count' => Discussion::where('parent', $this->id)->count(),
  34. 'created_at' => $this->created_at,
  35. 'updated_at' => $this->updated_at,
  36. ];
  37. $channels = [];
  38. switch ($this->res_type) {
  39. case 'sentence':
  40. $channelId = Sentence::where('uid', $this->res_id)->value('channel_uid');
  41. if (Str::isUuid($channelId)) {
  42. $channels[] = $channelId;
  43. }
  44. break;
  45. default:
  46. // code...
  47. break;
  48. }
  49. if (count($channels) > 0) {
  50. $data['html'] = MdRender::render($this->content, $channels, null, 'read');
  51. $data['summary'] = MdRender::render($this->content, $channels, null, 'read', 'translation', 'markdown', 'text');
  52. }
  53. return $data;
  54. }
  55. }