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

GetDomainEventsAction::__invoke()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 17
nc 2
nop 1
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\Symfony\HttpAction;
16
17
use Kreta\Notifier\Application\GetDomainEventsQuery;
18
use Kreta\SharedKernel\Application\QueryBus;
19
use Symfony\Component\HttpFoundation\JsonResponse;
20
use Symfony\Component\HttpFoundation\Request;
21
22
final class GetDomainEventsAction
23
{
24
    private const PAGE_SIZE = 25;
25
    private const CACHE_LIFETIME = 60 * 60 * 24 * 365; // 1 year
26
27
    private $queryBus;
28
29
    public function __construct(QueryBus $queryBus)
30
    {
31
        $this->queryBus = $queryBus;
32
    }
33
34
    public function __invoke(Request $request) : JsonResponse
35
    {
36
        $page = $request->query->getInt('page', 1);
37
        $since = $request->query->get('since');
38
39
        $this->queryBus->handle(
40
            new GetDomainEventsQuery(
41
                $page,
42
                self::PAGE_SIZE,
43
                $since
44
            ),
45
            $events
46
        );
47
48
        $numberOfEvents = count($events['data']);
49
        $isPageCompleted = $numberOfEvents === self::PAGE_SIZE;
50
        $response = new JsonResponse($events, 0 !== $numberOfEvents ? 200 : 404);
51
52
        if ($isPageCompleted) {
53
            $response
54
                ->setMaxAge(self::CACHE_LIFETIME)
55
                ->setSharedMaxAge(self::CACHE_LIFETIME);
56
        }
57
58
        return $response;
59
    }
60
}
61