Просмотр файла app/Controllers/TagController.php

Размер файла: 2.17Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Controllers;
  6.  
  7. use App\Models\Tag;
  8. use App\Repositories\StoryRepository;
  9. use App\Repositories\TagRepository;
  10. use App\Services\TagCloud;
  11. use App\Services\View;
  12. use Psr\Http\Message\ResponseInterface as Response;
  13. use Psr\Http\Message\ServerRequestInterface as Request;
  14.  
  15. /**
  16. * FavoriteController
  17. */
  18. class TagController extends Controller
  19. {
  20. public function __construct(
  21. protected View $view,
  22. protected TagRepository $tagRepository,
  23. protected StoryRepository $storyRepository,
  24. ) {}
  25.  
  26. /**
  27. * Tags
  28. *
  29. * @param Response $response
  30. * @param TagCloud $tagCloud
  31. *
  32. * @return Response
  33. */
  34. public function index(Response $response, TagCloud $tagCloud): Response
  35. {
  36. $tags = $this->tagRepository->getPopularTags(100);
  37.  
  38. $tags = $tagCloud->generate($tags);
  39.  
  40. return $this->view->render(
  41. $response,
  42. 'tags/tags',
  43. compact('tags')
  44. );
  45. }
  46.  
  47. /**
  48. * By tags
  49. *
  50. * @param string $tag
  51. * @param Response $response
  52. *
  53. * @return Response
  54. */
  55. public function search(string $tag, Response $response): Response
  56. {
  57. $tag = urldecode(escape($tag));
  58.  
  59. $stories = $this->storyRepository->getStoriesByTag($tag, setting('story.per_page'));
  60.  
  61. return $this->view->render(
  62. $response,
  63. 'tags/index',
  64. compact('stories', 'tag')
  65. );
  66. }
  67.  
  68. /**
  69. * Search by tag
  70. *
  71. * @param Request $request
  72. * @param Response $response
  73. *
  74. * @return Response
  75. */
  76. public function tag(Request $request, Response $response): Response
  77. {
  78. $query = $request->getQueryParams();
  79. $search = urldecode(escape($query['query'] ?? ''));
  80.  
  81. if (! $search) {
  82. return $this->json($response, []);
  83. }
  84.  
  85. $tags = Tag::query()->where('tag', 'like', $search . '%')->limit(10)->get();
  86. $tags = array_unique($tags->pluck('tag'));
  87.  
  88. $namedTags = [];
  89. foreach ($tags as $tag) {
  90. $namedTags[] = ['value' => $tag, 'label' => $tag];
  91. }
  92.  
  93. return $this->json($response, $namedTags);
  94. }
  95. }