1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Blog; |
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 BlogController extends Controller |
15
|
|
|
{ |
16
|
|
|
private const POSTS_PER_PAGE = 3; |
17
|
|
|
private const POPULAR_TAGS_COUNT = 10; |
18
|
|
|
|
19
|
|
|
protected function getId(): string |
20
|
|
|
{ |
21
|
|
|
return 'blog'; |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function index( |
25
|
|
|
Request $request, |
26
|
|
|
ORMInterface $orm, |
27
|
|
|
UrlGeneratorInterface $urlGenerator |
28
|
|
|
): Response { |
29
|
|
|
/** @var PostRepository $postRepo */ |
30
|
|
|
$postRepo = $orm->getRepository(Post::class); |
31
|
|
|
$tagRepo = $orm->getRepository(Tag::class); |
32
|
|
|
|
33
|
|
|
$pageNum = (int)$request->getAttribute('page', 1); |
34
|
|
|
$year = $request->getAttribute('year', null); |
35
|
|
|
$month = $request->getAttribute('month', null); |
36
|
|
|
$isArchive = $year !== null && $month !== null; |
37
|
|
|
|
38
|
|
|
$paginator = $isArchive |
39
|
|
|
? $postRepo->findArchivedPublic($year, $month) |
40
|
|
|
->withTokenGenerator(fn ($page) => $urlGenerator->generate( |
41
|
|
|
'blog/archive', |
42
|
|
|
['year' => $year, 'month' => $month, 'page' => $page] |
43
|
|
|
)) |
44
|
|
|
: $postRepo->findLastPublic() |
45
|
|
|
->withTokenGenerator(fn ($page) => $urlGenerator->generate('blog/index', ['page' => $page])); |
46
|
|
|
|
47
|
|
|
$paginator = $paginator |
48
|
|
|
->withPageSize(self::POSTS_PER_PAGE) |
49
|
|
|
->withCurrentPage($pageNum); |
50
|
|
|
|
51
|
|
|
$data = [ |
52
|
|
|
'paginator' => $paginator, |
53
|
|
|
'archive' => $postRepo->getArchive(), |
54
|
|
|
'tags' => $tagRepo->getTagMentions(self::POPULAR_TAGS_COUNT), |
|
|
|
|
55
|
|
|
]; |
56
|
|
|
$output = $this->render('index', $data); |
57
|
|
|
|
58
|
|
|
$response = $this->responseFactory->createResponse(); |
59
|
|
|
$response->getBody()->write($output); |
60
|
|
|
return $response; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|