CommentTransformer.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. }else{
  25. $replies = PostComment::where('parent_id', $postComment['id'])->orderBy('id', 'desc')->limit(2)->get();
  26. foreach($replies as $val){
  27. $userComment = $this->userInfo($val->uid);
  28. $replyUsername = '';
  29. if($val->reply_uid){
  30. $userReply = $this->userInfo($val->reply_uid);
  31. $replyUsername = $userReply['username'];
  32. }
  33. $reply[] = [
  34. 'uid' => $val->uid,
  35. 'username' => $userComment['username'],
  36. 'avatar' => $userComment['avatar'],
  37. 'reply_username' => $replyUsername,
  38. 'content' => $val->is_delete?'该评论已被删除':$val->content,
  39. 'created_at' => Carbon::parse($val->created_at)->diffForHumans(),
  40. 'is_delete' => $val->is_delete,
  41. ];
  42. }
  43. Redis::SET($replyKey, json_encode($reply));
  44. Redis::EXPIRE($replyKey, 604800);
  45. }
  46. $user = $this->userInfo($postComment['uid']);
  47. return [
  48. 'id' => $postComment['id'],
  49. 'uid' => $postComment['uid'],
  50. 'username' => $user['username'],
  51. 'avatar' => $user['avatar'],
  52. 'content' => $postComment['is_delete']?'该评论已被删除':$postComment['content'],
  53. 'created_at' => Carbon::parse($postComment['created_at'])->diffForHumans(),
  54. 'reply_count' => $postComment['reply_count'],
  55. 'reply' => $reply,
  56. 'is_delete' => $postComment['is_delete'],
  57. ];
  58. }
  59. }