1
0

SearchController.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Auth;
  4. use App\Hashtag;
  5. use App\Profile;
  6. use App\Status;
  7. use Illuminate\Http\Request;
  8. use Illuminate\Support\Facades\Cache;
  9. class SearchController extends Controller
  10. {
  11. public function __construct()
  12. {
  13. $this->middleware('auth');
  14. }
  15. public function searchAPI(Request $request, $tag)
  16. {
  17. if(mb_strlen($tag) < 3) {
  18. return;
  19. }
  20. $hash = hash('sha256', $tag);
  21. $tokens = Cache::remember('api:search:tag:'.$hash, 60, function () use ($tag) {
  22. $tokens = collect([]);
  23. $hashtags = Hashtag::select('id', 'name', 'slug')->where('slug', 'like', '%'.$tag.'%')->limit(20)->get();
  24. if($hashtags->count() > 0) {
  25. $tags = $hashtags->map(function ($item, $key) {
  26. return [
  27. 'count' => $item->posts()->count(),
  28. 'url' => $item->url(),
  29. 'type' => 'hashtag',
  30. 'value' => $item->name,
  31. 'tokens' => explode('-', $item->name),
  32. 'name' => null,
  33. ];
  34. });
  35. $tokens->push($tags);
  36. }
  37. $users = Profile::select('username', 'name', 'id')
  38. ->where('username', 'like', '%'.$tag.'%')
  39. ->limit(20)
  40. ->get();
  41. if($users->count() > 0) {
  42. $profiles = $users->map(function ($item, $key) {
  43. return [
  44. 'count' => 0,
  45. 'url' => $item->url(),
  46. 'type' => 'profile',
  47. 'value' => $item->username,
  48. 'tokens' => [$item->username],
  49. 'name' => $item->name,
  50. ];
  51. });
  52. $tokens->push($profiles);
  53. }
  54. return $tokens;
  55. });
  56. $posts = Status::select('id', 'profile_id', 'caption', 'created_at')
  57. ->whereHas('media')
  58. ->whereNull('in_reply_to_id')
  59. ->whereNull('reblog_of_id')
  60. ->whereProfileId(Auth::user()->profile->id)
  61. ->where('caption', 'like', '%'.$tag.'%')
  62. ->orderBy('created_at', 'desc')
  63. ->get();
  64. if($posts->count() > 0) {
  65. $posts = $posts->map(function($item, $key) {
  66. return [
  67. 'count' => 0,
  68. 'url' => $item->url(),
  69. 'type' => 'status',
  70. 'value' => "by {$item->profile->username} <span class='float-right'>{$item->created_at->diffForHumans(null, true, true)}</span>",
  71. 'tokens' => [$item->caption],
  72. 'name' => $item->caption,
  73. 'thumb' => $item->thumb(),
  74. ];
  75. });
  76. $tokens = $tokens->push($posts);
  77. }
  78. if($tokens->count() > 0) {
  79. $tokens = $tokens[0];
  80. }
  81. return response()->json($tokens);
  82. }
  83. }