Passed
Pull Request — master (#49)
by
unknown
11:28
created

TagController::getId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
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 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 TagController extends Controller
18
{
19
    private const POSTS_PER_PAGE = 10;
20
21
    protected function getId(): string
22
    {
23
        return 'blog/tag';
24
    }
25
26
    public function index(
27
        Request $request,
28
        ORMInterface $orm,
29
        UrlGeneratorInterface $urlGenerator
30
    ): Response {
31
        /** @var TagRepository $tagRepo */
32
        $tagRepo = $orm->getRepository(Tag::class);
33
        /** @var PostRepository $postRepo */
34
        $postRepo = $orm->getRepository(Post::class);
35
        $label = $request->getAttribute('label', null);
36
        $pageNum = (int)$request->getAttribute('page', 1);
37
38
        $item = $tagRepo->findByLabel($label);
39
40
        if ($item === null) {
41
            return $this->responseFactory->createResponse(404);
42
        }
43
        // preloading of posts
44
        $paginator = (new OffsetPaginator(
45
            $postRepo->findByTag($item->getId())
46
                     ->withSort((new Sort([]))->withOrder(['published_at' => 'desc']))
47
        ))
48
            ->withPageSize(self::POSTS_PER_PAGE)
49
            ->withCurrentPage($pageNum);
50
        $pageUrlGenerator = fn ($page) => $urlGenerator->generate(
51
            'blog/tag',
52
            ['label' => $label, 'page' => $page]
53
        );
54
55
        $data = [
56
            'item' => $item,
57
            'paginationSet' => new PaginationSet($paginator, $pageUrlGenerator),
0 ignored issues
show
Deprecated Code introduced by
The class App\Pagination\PaginationSet has been deprecated: Should be replaced to a Pagination Widget ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

57
            'paginationSet' => /** @scrutinizer ignore-deprecated */ new PaginationSet($paginator, $pageUrlGenerator),
Loading history...
58
        ];
59
        $output = $this->render(__FUNCTION__, $data);
60
61
        $response = $this->responseFactory->createResponse();
62
        $response->getBody()->write($output);
63
        return $response;
64
    }
65
}
66