TopicPagesResponse.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * 话题分页返回封装.
  4. *
  5. * @author nj <nj@gmail.com>
  6. * @date 2020-01-28 20:46:56
  7. */
  8. declare(strict_types=1);
  9. namespace Modules\Api\Responses;
  10. use App\Contracts\Responsable;
  11. class TopicPagesResponse implements Responsable
  12. {
  13. /**
  14. * 录入的数据.
  15. *
  16. * @var mixed
  17. */
  18. private $data = null;
  19. /**
  20. * 附加条件参数.
  21. *
  22. * @var array
  23. */
  24. private $params = [];
  25. public function __construct($data = null, $params = [])
  26. {
  27. $this->data = $data;
  28. $this->params = $params;
  29. }
  30. public function toResponse(
  31. $request = null
  32. ) {
  33. $data = [];
  34. $result = $this->data->toArray();
  35. if (!empty($result['data'])) {
  36. foreach ($result['data'] as $k => $v) {
  37. $user = !empty($v['user']) ? collect($v['user'])->only([
  38. 'nick', 'avatar', 'code',
  39. ]) : [];
  40. $category = !empty($v['category']) ? collect($v['category'])->only([
  41. 'id', 'name', 'cover_pic', ' total_topic',
  42. ]) : [];
  43. $data[$k] = collect($v)->only([
  44. 'id', 'created_at', 'user_id', 'category_id', 'content', 'ct_type', 'cover_pic', 'video_id',
  45. 'total_comment', 'total_share', 'total_support', 'is_top', 'is_digest', 'sticked_at',
  46. ]);
  47. if (empty($v['sdata'])) {
  48. $jdata = [];
  49. } else {
  50. $jdata = json_decode($v['sdata'], true);
  51. }
  52. if (empty($jdata)) {
  53. // 当数据是空的时候,为了前端识别固定类型,强制转空对象.
  54. $jdata = new \stdClass();
  55. }
  56. $data[$k]['user'] = $user;
  57. $data[$k]['category'] = $category;
  58. $data[$k]['jdata'] = $jdata;
  59. }
  60. }
  61. $result['data'] = $data;
  62. unset($v, $user, $category, $jdata);
  63. return json_success($result);
  64. }
  65. }