Passed
Pull Request — master (#49)
by
unknown
17:14 queued 02:12
created

TagController   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 3
eloc 20
c 2
b 0
f 0
dl 0
loc 37
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getId() 0 3 1
A index() 0 28 2
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