Completed
Push — master ( 263533...6dddbe )
by Beñat
01:46
created

GetEvents   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 58
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A __invoke() 0 12 1
A response() 0 11 1
A numberOfEvents() 0 4 1
A links() 0 16 2
1
<?php
2
3
/*
4
 * This file is part of the Shared Kernel library.
5
 *
6
 * Copyright (c) 2016-present LIN3S <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace LIN3S\SharedKernel\Application\Event;
15
16
use LIN3S\SharedKernel\Domain\Model\EventsUrlGenerator;
17
use LIN3S\SharedKernel\Event\EventStore;
18
19
/**
20
 * @author Beñat Espiña <[email protected]>
21
 */
22
class GetEvents
23
{
24
    private $eventStore;
25
    private $urlGenerator;
26
27
    public function __construct(EventStore $eventStore, EventsUrlGenerator $urlGenerator)
28
    {
29
        $this->eventStore = $eventStore;
30
        $this->urlGenerator = $urlGenerator;
31
    }
32
33
    public function __invoke(GetEventsQuery $query) : array
34
    {
35
        $page = $query->page();
36
        $pageSize = $query->pageSize();
37
        $since = $query->since();
38
39
        $offset = ($page - 1) * $pageSize;
40
41
        $events = $this->eventStore->eventsSince($since, $offset, $pageSize);
42
43
        return $this->response($events, $page, $pageSize);
44
    }
45
46
    public function response(array $events, int $page, int $pageSize) : array
47
    {
48
        return [
49
            '_meta'  => [
50
                'count' => $this->numberOfEvents($events),
51
                'page'  => $page,
52
            ],
53
            '_links' => $this->links($events, $page, $pageSize),
54
            'data'   => $events,
55
        ];
56
    }
57
58
    private function numberOfEvents(array $events) : int
59
    {
60
        return count($events);
61
    }
62
63
    private function links(array $events, int $page, int $pageSize) : array
64
    {
65
        $links = [
66
            'first' => $this->urlGenerator->generate(1),
67
            'self'  => $this->urlGenerator->generate($page),
68
        ];
69
        if ($this->numberOfEvents($events) === $pageSize) {
70
            $links = array_merge(
71
                ['first' => $this->urlGenerator->generate(1)],
72
                ['self' => $links['self']],
73
                ['next' => $this->urlGenerator->generate($page + 1)]
74
            );
75
        }
76
77
        return $links;
78
    }
79
}
80