Passed
Pull Request — master (#5629)
by Angel Fernando Quiroz
08:49
created

VersionListener   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 43
rs 10
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A onKernelResponse() 0 14 4
A onKernelRequest() 0 25 6
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the xAPI package.
7
 *
8
 * (c) Christian Flothmann <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace XApi\LrsBundle\EventListener;
15
16
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
17
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
18
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
19
20
/**
21
 * @author Jérôme Parmentier <[email protected]>
22
 */
23
class VersionListener
24
{
25
    public function onKernelRequest(GetResponseEvent $event): void
26
    {
27
        if (!$event->isMasterRequest()) {
28
            return;
29
        }
30
31
        $request = $event->getRequest();
32
33
        if (!$request->attributes->has('xapi_lrs.route')) {
34
            return;
35
        }
36
37
        if (null === $version = $request->headers->get('X-Experience-API-Version')) {
38
            throw new BadRequestHttpException('Missing required "X-Experience-API-Version" header.');
39
        }
40
41
        if (preg_match('/^1\.0(?:\.\d+)?$/', $version)) {
42
            if ('1.0' === $version) {
43
                $request->headers->set('X-Experience-API-Version', '1.0.0');
44
            }
45
46
            return;
47
        }
48
49
        throw new BadRequestHttpException(sprintf('xAPI version "%s" is not supported.', $version));
50
    }
51
52
    public function onKernelResponse(FilterResponseEvent $event): void
53
    {
54
        if (!$event->isMasterRequest()) {
55
            return;
56
        }
57
58
        if (!$event->getRequest()->attributes->has('xapi_lrs.route')) {
59
            return;
60
        }
61
62
        $headers = $event->getResponse()->headers;
63
64
        if (!$headers->has('X-Experience-API-Version')) {
65
            $headers->set('X-Experience-API-Version', '1.0.3');
66
        }
67
    }
68
}
69