UserDictResource.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Http\Resources;
  3. use App\Http\Api\MdRender;
  4. use App\Http\Api\UserApi;
  5. use App\Models\DictInfo;
  6. use App\Models\UserOperationDaily;
  7. use Illuminate\Contracts\Support\Arrayable;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Http\Resources\Json\JsonResource;
  10. class UserDictResource extends JsonResource
  11. {
  12. /**
  13. * Transform the resource into an array.
  14. *
  15. * @param Request $request
  16. * @return array|Arrayable|\JsonSerializable
  17. */
  18. public function toArray($request)
  19. {
  20. $data = [
  21. 'id' => $this->id,
  22. 'word' => $this->word,
  23. 'type' => $this->type,
  24. 'grammar' => $this->grammar,
  25. 'mean' => $this->mean,
  26. 'parent' => $this->parent,
  27. 'note' => $this->note,
  28. 'factors' => $this->factors,
  29. 'source' => $this->source,
  30. 'status' => $this->status,
  31. 'confidence' => $this->confidence,
  32. 'updated_at' => $this->updated_at,
  33. 'creator_id' => $this->creator_id,
  34. ];
  35. if (! empty($this->note)) {
  36. $mdRender = new MdRender(['format' => 'react', 'lang' => 'zh-Hans']);
  37. $data['note'] = $mdRender->convert($this->note);
  38. }
  39. if ($request->input('view') === 'community') {
  40. $data['editor'] = UserApi::getById($this->creator_id);
  41. // 毫秒计算的经验值
  42. $exp = UserOperationDaily::where('user_id', $this->creator_id)
  43. ->where('date_int', '<=', date_timestamp_get(date_create($this->updated_at)) * 1000)
  44. ->sum('duration');
  45. $data['exp'] = (int) ($exp / 1000);
  46. }
  47. if ($request->input('view') === 'all') {
  48. $data['dict'] = DictInfo::where('id', $this->dict_id)->select(['id', 'name', 'shortname'])->first();
  49. }
  50. return $data;
  51. }
  52. }