Completed
Push — master ( 4be545...15ae11 )
by Beñat
01:37
created

ListEventsAction::cachedResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
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\Infrastructure\Symfony\HttpAction;
15
16
use LIN3S\SharedKernel\Application\Event\GetEvents;
17
use LIN3S\SharedKernel\Application\Event\GetEventsQuery;
18
use Symfony\Component\HttpFoundation\JsonResponse;
19
use Symfony\Component\HttpFoundation\Request;
20
use Symfony\Component\HttpFoundation\Response;
21
22
/**
23
 * @author Beñat Espiña <[email protected]>
24
 */
25
class ListEventsAction
26
{
27
    private const PAGE_SIZE = 25;
28
    private const CACHE_LIFETIME = 60 * 60 * 24 * 365; // 1 year
29
30
    private $getEvents;
31
32
    public function __construct(GetEvents $getEvents)
33
    {
34
        $this->getEvents = $getEvents;
35
    }
36
37
    public function __invoke(Request $request) : JsonResponse
38
    {
39
        $page = $request->query->getInt('page', 1);
40
        $since = $request->query->get('since');
41
42
        $events = $this->getEvents->__invoke(new GetEventsQuery($page, self::PAGE_SIZE, $since));
43
44
        $numberOfEvents = count($events['data']);
45
        $isPageCompleted = $numberOfEvents === self::PAGE_SIZE;
46
        $response = new JsonResponse($events, 0 !== $numberOfEvents ? 200 : 404);
47
48
        return $isPageCompleted ? $this->cachedResponse($response) : $response;
49
    }
50
51
    private function cachedResponse(Response $response) : Response
52
    {
53
        return $response
54
            ->setMaxAge(self::CACHE_LIFETIME)
55
            ->setSharedMaxAge(self::CACHE_LIFETIME);
56
    }
57
}
58