|
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\Data\Paginator\OffsetPaginator; |
|
13
|
|
|
use Yiisoft\Router\UrlGeneratorInterface; |
|
14
|
|
|
|
|
15
|
|
|
final class TagController extends Controller |
|
16
|
|
|
{ |
|
17
|
|
|
private const POSTS_PER_PAGE = 10; |
|
18
|
|
|
|
|
19
|
|
|
protected function getId(): string |
|
20
|
|
|
{ |
|
21
|
|
|
return 'blog/tag'; |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
public function index(Request $request, ORMInterface $orm): Response |
|
25
|
|
|
{ |
|
26
|
|
|
/** @var TagRepository $tagRepo */ |
|
27
|
|
|
$tagRepo = $orm->getRepository(Tag::class); |
|
28
|
|
|
/** @var PostRepository $postRepo */ |
|
29
|
|
|
$postRepo = $orm->getRepository(Post::class); |
|
30
|
|
|
$label = $request->getAttribute('label', null); |
|
31
|
|
|
$pageNum = (int)$request->getAttribute('page', 1); |
|
32
|
|
|
|
|
33
|
|
|
$item = $tagRepo->findByLabel($label); |
|
34
|
|
|
|
|
35
|
|
|
if ($item === null) { |
|
36
|
|
|
return $this->responseFactory->createResponse(404); |
|
37
|
|
|
} |
|
38
|
|
|
// preloading of posts |
|
39
|
|
|
$paginator = (new OffsetPaginator($postRepo->findByTag($item->getId()))) |
|
40
|
|
|
->withPageSize(self::POSTS_PER_PAGE) |
|
41
|
|
|
->withCurrentPage($pageNum); |
|
42
|
|
|
|
|
43
|
|
|
$data = [ |
|
44
|
|
|
'item' => $item, |
|
45
|
|
|
'paginator' => $paginator, |
|
46
|
|
|
]; |
|
47
|
|
|
$output = $this->render(__FUNCTION__, $data); |
|
48
|
|
|
|
|
49
|
|
|
$response = $this->responseFactory->createResponse(); |
|
50
|
|
|
$response->getBody()->write($output); |
|
51
|
|
|
return $response; |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|