Completed
Push — master ( 1c14d6...2c9995 )
by Dawid
02:08
created

ApiVersionListener::getAnnotationReader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiechu\SymfonyCommonsBundle\EventListener;
6
7
use Doctrine\Common\Annotations\Reader;
8
use Spiechu\SymfonyCommonsBundle\Annotation\Controller\ApiVersion;
9
use Spiechu\SymfonyCommonsBundle\Annotation\Controller\ControllerAnnotationExtractorTrait;
10
use Spiechu\SymfonyCommonsBundle\Event\ApiVersion\ApiVersionSetEvent;
11
use Spiechu\SymfonyCommonsBundle\Event\ApiVersion\Events;
12
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
13
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
14
15
class ApiVersionListener
16
{
17
    use ControllerAnnotationExtractorTrait;
18
19
    const ATTRIBUTE_API_VERSION = 'spiechu_symfony_commons.event_listener.api_version';
20
21
    /** @var Reader */
22
    protected $annotationReader;
23
24
    /** @var EventDispatcherInterface */
25
    protected $eventDispatcher;
26
27
    /**
28
     * @param Reader                   $annotationReader
29
     * @param EventDispatcherInterface $eventDispatcher
30
     */
31
    public function __construct(Reader $annotationReader, EventDispatcherInterface $eventDispatcher)
32
    {
33
        $this->annotationReader = $annotationReader;
34
        $this->eventDispatcher = $eventDispatcher;
35
    }
36
37
    /**
38
     * @param FilterControllerEvent $event
39
     *
40
     * @throws \InvalidArgumentException
41
     */
42
    public function onKernelController(FilterControllerEvent $event): void
43
    {
44
        $apiVersion = $this->getApiVersionFromController($event->getController());
45
46
        if (!$apiVersion instanceof ApiVersion) {
47
            return;
48
        }
49
50
        $event->getRequest()->attributes->set(self::ATTRIBUTE_API_VERSION, $apiVersion->getApiVersion());
51
52
        $this->eventDispatcher->dispatch(Events::API_VERSION_SET, new ApiVersionSetEvent($apiVersion));
53
    }
54
55
    /**
56
     * @param null|callable $controller
57
     *
58
     * @return null|ApiVersion
59
     */
60
    protected function getApiVersionFromController(?callable $controller): ?ApiVersion
61
    {
62
        return $this->getClassAnnotationFromController($controller, ApiVersion::class);
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    protected function getAnnotationReader(): Reader
69
    {
70
        return $this->annotationReader;
71
    }
72
}
73