Completed
Pull Request — 2.x (#2288)
by Guilhem
17:20
created

VersionListener::onKernelRequest()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.0187

Importance

Changes 0
Metric Value
dl 0
loc 21
ccs 10
cts 11
cp 0.9091
rs 9.2728
c 0
b 0
f 0
cc 5
nc 5
nop 1
crap 5.0187
1
<?php
2
3
/*
4
 * This file is part of the FOSRestBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
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
namespace FOS\RestBundle\EventListener;
13
14
use FOS\RestBundle\FOSRestBundle;
15
use FOS\RestBundle\Version\VersionResolverInterface;
16
use Symfony\Component\HttpKernel\Event\RequestEvent;
17
18
/**
19
 * @internal
20
 */
21
class VersionListener
22
{
23
    private $versionResolver;
24
    private $defaultVersion;
25
26 8
    public function __construct(VersionResolverInterface $versionResolver, ?string $defaultVersion = null)
27
    {
28 8
        $this->versionResolver = $versionResolver;
29 8
        $this->defaultVersion = $defaultVersion;
30 8
    }
31
32 8
    public function onKernelRequest(RequestEvent $event): void
33
    {
34 8
        $request = $event->getRequest();
35
36 8
        if (!$request->attributes->get(FOSRestBundle::ZONE_ATTRIBUTE, true)) {
37 1
            return;
38
        }
39
40 7
        $version = $this->versionResolver->resolve($request);
41
42 7
        if (null === $version && null !== $this->defaultVersion) {
43 3
            $version = $this->defaultVersion;
44
        }
45
46
        // Return if nothing to do
47 7
        if (null === $version) {
48
            return;
49
        }
50
51 7
        $request->attributes->set('version', $version);
52 7
    }
53
}
54