|
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
|
|
|
protected 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
|
20 |
|
public function __construct(Reader $annotationReader, EventDispatcherInterface $eventDispatcher) |
|
32
|
|
|
{ |
|
33
|
20 |
|
$this->annotationReader = $annotationReader; |
|
34
|
20 |
|
$this->eventDispatcher = $eventDispatcher; |
|
35
|
20 |
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* @param FilterControllerEvent $event |
|
39
|
|
|
* |
|
40
|
|
|
* @throws \InvalidArgumentException |
|
41
|
|
|
*/ |
|
42
|
20 |
|
public function onKernelController(FilterControllerEvent $event): void |
|
43
|
|
|
{ |
|
44
|
20 |
|
$apiVersion = $this->getApiVersionFromController($event->getController()); |
|
45
|
|
|
|
|
46
|
20 |
|
if (!$apiVersion instanceof ApiVersion) { |
|
47
|
7 |
|
return; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
13 |
|
$event->getRequest()->attributes->set(static::ATTRIBUTE_API_VERSION, $apiVersion->getApiVersion()); |
|
51
|
|
|
|
|
52
|
13 |
|
$this->eventDispatcher->dispatch(Events::API_VERSION_SET, new ApiVersionSetEvent($apiVersion)); |
|
|
|
|
|
|
53
|
13 |
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* @param callable $controller |
|
57
|
|
|
* |
|
58
|
|
|
* @return null|ApiVersion |
|
59
|
|
|
*/ |
|
60
|
20 |
|
protected function getApiVersionFromController(callable $controller): ?ApiVersion |
|
61
|
|
|
{ |
|
62
|
20 |
|
return $this->getClassAnnotationFromController($controller, ApiVersion::class); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* {@inheritdoc} |
|
67
|
|
|
*/ |
|
68
|
20 |
|
protected function getAnnotationReader(): Reader |
|
69
|
|
|
{ |
|
70
|
20 |
|
return $this->annotationReader; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|