forked from FriendsOfSymfony/FOSRestBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVersionListener.php
86 lines (74 loc) · 2.46 KB
/
VersionListener.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
/*
* This file is part of the FOSRestBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\RestBundle\EventListener;
use FOS\RestBundle\Version\VersionResolverInterface;
use FOS\RestBundle\View\ConfigurableViewHandlerInterface;
use FOS\RestBundle\View\ViewHandlerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
/**
* @internal
*/
class VersionListener
{
private $viewHandler;
private $regex;
private $version = false;
private $versionResolver;
private $defaultVersion;
public function __construct(ViewHandlerInterface $viewHandler, VersionResolverInterface $versionResolver = null, $defaultVersion = null)
{
$this->viewHandler = $viewHandler;
$this->versionResolver = $versionResolver;
$this->defaultVersion = $defaultVersion;
}
/**
* Gets the version.
*
* @return mixed
*/
public function getVersion()
{
return $this->version;
}
/**
* Sets the regex.
*
* @param string $regex
*/
public function setRegex($regex)
{
$this->regex = $regex;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (null !== $this->regex) {
$mediaType = $request->attributes->get('media_type');
if (1 === preg_match($this->regex, $mediaType, $matches)) {
$this->version = $matches['version'];
$request->attributes->set('version', $this->version);
if ($this->viewHandler instanceof ConfigurableViewHandlerInterface) {
$this->viewHandler->setExclusionStrategyVersion($this->version);
}
}
} elseif (null !== $this->versionResolver) {
$this->version = $this->versionResolver->resolve($request);
if (false === $this->version && null !== $this->defaultVersion) {
$this->version = $this->defaultVersion;
}
if (false !== $this->version) {
$request->attributes->set('version', $this->version);
if ($this->viewHandler instanceof ConfigurableViewHandlerInterface) {
$this->viewHandler->setExclusionStrategyVersion($this->version);
}
}
}
}
}