CommentTransformer.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Administrator
  5. * Date: 2019/6/15
  6. * Time: 16:40
  7. */
  8. namespace App\Transformers\Post;
  9. use App\Models\PostComment;
  10. use App\Traits\UserTrait;
  11. use Carbon\Carbon;
  12. use Illuminate\Support\Facades\Redis;
  13. use League\Fractal\TransformerAbstract;
  14. class CommentTransformer extends TransformerAbstract
  15. {
  16. use UserTrait;
  17. public function transform(PostComment $postComment)
  18. {
  19. $reply = [];
  20. $replyKey = 'post_new_reply_'.$postComment['id'];
  21. $replyData = Redis::GET($replyKey);
  22. if($replyData){
  23. $reply = json_decode($replyData);
  24. foreach($reply as &$item){
  25. $item['created_at'] = Carbon::parse($item['created_at'])->diffForHumans();
  26. }
  27. }else{
  28. $replies = PostComment::where('parent_id', $postComment['id'])->orderBy('id', 'desc')->limit(2)->get();
  29. foreach($replies as $val){
  30. $userComment = $this->userInfo($val->uid);
  31. $replyUsername = '';
  32. if($val->reply_uid){
  33. $userReply = $this->userInfo($val->reply_uid);
  34. $replyUsername = $userReply['username'];
  35. }
  36. $reply[] = [
  37. 'uid' => $val->uid,
  38. 'username' => $userComment['username'],
  39. 'avatar' => $userComment['avatar'],
  40. 'reply_username' => $replyUsername,
  41. 'content' => $val->is_delete?'该评论已被删除':$val->content,
  42. 'created_at' => Carbon::parse($val->created_at)->diffForHumans(),
  43. 'is_delete' => $val->is_delete,
  44. ];
  45. }
  46. Redis::SET($replyKey, json_encode($reply));
  47. Redis::EXPIRE($replyKey, 604800);
  48. }
  49. $user = $this->userInfo($postComment['uid']);
  50. return [
  51. 'id' => $postComment['id'],
  52. 'uid' => $postComment['uid'],
  53. 'username' => $user['username'],
  54. 'avatar' => $user['avatar'],
  55. 'content' => $postComment['is_delete']?'该评论已被删除':$postComment['content'],
  56. 'created_at' => Carbon::parse($postComment['created_at'])->diffForHumans(),
  57. 'reply_count' => $postComment['reply_count'],
  58. 'reply' => $reply,
  59. 'is_delete' => $postComment['is_delete'],
  60. ];
  61. }
  62. }