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 App\Pagination\PaginationSet; |
10
|
|
|
use Cycle\ORM\ORMInterface; |
11
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
12
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
13
|
|
|
use Yiisoft\Data\Paginator\OffsetPaginator; |
14
|
|
|
use Yiisoft\Data\Reader\Sort; |
15
|
|
|
use Yiisoft\Router\UrlGeneratorInterface; |
16
|
|
|
|
17
|
|
|
class BlogController extends Controller |
18
|
|
|
{ |
19
|
|
|
private const POSTS_PER_PAGE = 3; |
20
|
|
|
private const POPULAR_TAGS_COUNT = 10; |
21
|
|
|
|
22
|
|
|
protected function getId(): string |
23
|
|
|
{ |
24
|
|
|
return 'blog'; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function index( |
28
|
|
|
Request $request, |
29
|
|
|
ORMInterface $orm, |
30
|
|
|
UrlGeneratorInterface $urlGenerator |
31
|
|
|
): Response { |
32
|
|
|
/** @var PostRepository $postRepo */ |
33
|
|
|
$postRepo = $orm->getRepository(Post::class); |
34
|
|
|
$tagRepo = $orm->getRepository(Tag::class); |
35
|
|
|
|
36
|
|
|
$pageNum = (int)$request->getAttribute('page', 1); |
37
|
|
|
$year = $request->getAttribute('year', null); |
38
|
|
|
$month = $request->getAttribute('month', null); |
39
|
|
|
$isArchive = $year !== null && $month !== null; |
40
|
|
|
|
41
|
|
|
if ($isArchive) { |
42
|
|
|
$dataReader = $postRepo->findArchivedPublic($year, $month); |
43
|
|
|
$pageUrlGenerator = fn ($page) => $urlGenerator->generate( |
44
|
|
|
'blog/archive', |
45
|
|
|
['year' => $year, 'month' => $month, 'page' => $page] |
46
|
|
|
); |
47
|
|
|
} else { |
48
|
|
|
$dataReader = $postRepo->findAllPreloaded(); |
49
|
|
|
$pageUrlGenerator = fn ($page) => $urlGenerator->generate('blog/index', ['page' => $page]); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$paginationSet = new PaginationSet( |
|
|
|
|
53
|
|
|
(new OffsetPaginator($dataReader->withSort((new Sort([]))->withOrder(['published_at' => 'desc'])))) |
54
|
|
|
->withPageSize(self::POSTS_PER_PAGE) |
55
|
|
|
->withCurrentPage($pageNum), |
56
|
|
|
$pageUrlGenerator |
57
|
|
|
); |
58
|
|
|
|
59
|
|
|
$data = [ |
60
|
|
|
'paginationSet' => $paginationSet, |
61
|
|
|
'archive' => $postRepo->getArchive(), |
62
|
|
|
'tags' => $tagRepo->getTagMentions(self::POPULAR_TAGS_COUNT), |
|
|
|
|
63
|
|
|
]; |
64
|
|
|
$output = $this->render('index', $data); |
65
|
|
|
|
66
|
|
|
$response = $this->responseFactory->createResponse(); |
67
|
|
|
$response->getBody()->write($output); |
68
|
|
|
return $response; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|