Completed
Push — master ( 7fe5eb...9bad48 )
by Beñat
08:54 queued 04:27
created

SymfonyRouterGetDomainEventsResponse::links()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 3
1
<?php
2
3
/*
4
 * This file is part of the Kreta package.
5
 *
6
 * (c) Beñat Espiña <[email protected]>
7
 * (c) Gorka Laucirica <[email protected]>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
declare(strict_types=1);
14
15
namespace Kreta\Notifier\Infrastructure\Application;
16
17
use Kreta\Notifier\Application\GetDomainEventsResponse;
18
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
19
20
class SymfonyRouterGetDomainEventsResponse implements GetDomainEventsResponse
21
{
22
    private $urlGenerator;
23
24
    public function __construct(UrlGeneratorInterface $urlGenerator)
25
    {
26
        $this->urlGenerator = $urlGenerator;
27
    }
28
29
    public function build(array $events, int $page, int $pageSize) : array
30
    {
31
        return [
32
            '_meta'  => [
33
                'count' => $this->numberOfEvents($events),
34
                'page'  => $page,
35
            ],
36
            '_links' => $this->links($events, $page, $pageSize),
37
            'data'   => $events,
38
        ];
39
    }
40
41
    private function numberOfEvents(array $events) : int
42
    {
43
        return count($events);
44
    }
45
46
    private function links(array $events, int $page, int $pageSize) : array
47
    {
48
        $links = [
49
            'first' => $this->urlGenerate(1),
50
            'self'  => $this->urlGenerate($page),
51
        ];
52
53
        if ($this->numberOfEvents($events) === $pageSize) {
54
            $links = array_merge(
55
                ['first' => $this->urlGenerate(1)],
56
                ['self' => $links['self']],
57
                ['next' => $this->urlGenerate($page + 1)]
58
            );
59
        }
60
61
        return $links;
62
    }
63
64
    private function urlGenerate(int $page) : string
65
    {
66
        return $this->urlGenerator->generate(
67
            'kreta_notifier_get_domain_events',
68
            ['page' => $page],
69
            UrlGeneratorInterface::ABSOLUTE_URL
70
        );
71
    }
72
}
73