1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Blog\Tag; |
4
|
|
|
|
5
|
|
|
use App\Controller; |
6
|
|
|
use App\Blog\Entity\Post; |
7
|
|
|
use App\Blog\Entity\Tag; |
8
|
|
|
use App\Blog\Post\PostRepository; |
9
|
|
|
use Cycle\ORM\ORMInterface; |
10
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
11
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
12
|
|
|
use Yiisoft\Router\UrlGeneratorInterface; |
13
|
|
|
|
14
|
|
|
class TagController extends Controller |
15
|
|
|
{ |
16
|
|
|
private const POSTS_PER_PAGE = 10; |
17
|
|
|
private const POPULAR_TAGS_COUNT = 10; |
18
|
|
|
|
19
|
|
|
protected function getId(): string |
20
|
|
|
{ |
21
|
|
|
return 'blog/tag'; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function index( |
25
|
|
|
Request $request, |
26
|
|
|
ORMInterface $orm, |
27
|
|
|
UrlGeneratorInterface $urlGenerator |
28
|
|
|
): Response { |
29
|
|
|
/** @var TagRepository $tagRepo */ |
30
|
|
|
$tagRepo = $orm->getRepository(Tag::class); |
31
|
|
|
/** @var PostRepository $postRepo */ |
32
|
|
|
$postRepo = $orm->getRepository(Post::class); |
33
|
|
|
$label = $request->getAttribute('label', null); |
34
|
|
|
$pageNum = (int)$request->getAttribute('page', 1); |
35
|
|
|
|
36
|
|
|
$item = $tagRepo->findByLabel($label); |
37
|
|
|
|
38
|
|
|
if ($item === null) { |
39
|
|
|
return $this->responseFactory->createResponse(404); |
40
|
|
|
} |
41
|
|
|
// preloading of posts |
42
|
|
|
$paginator = $postRepo |
43
|
|
|
->findByTag($item->getId()) |
44
|
|
|
->withTokenGenerator(fn ($page) => $urlGenerator->generate( |
45
|
|
|
'blog/tag', |
46
|
|
|
['label' => $label, 'page' => $page] |
47
|
|
|
)) |
48
|
|
|
->withPageSize(self::POSTS_PER_PAGE) |
49
|
|
|
->withCurrentPage($pageNum); |
50
|
|
|
|
51
|
|
|
$data = [ |
52
|
|
|
'item' => $item, |
53
|
|
|
'paginator' => $paginator, |
54
|
|
|
]; |
55
|
|
|
$output = $this->render(__FUNCTION__, $data); |
56
|
|
|
|
57
|
|
|
$response = $this->responseFactory->createResponse(); |
58
|
|
|
$response->getBody()->write($output); |
59
|
|
|
return $response; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|