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\Util\StopFormatListenerException; |
16
|
|
|
use FOS\RestBundle\Negotiation\FormatNegotiator; |
17
|
|
|
use Symfony\Component\HttpKernel\Event\RequestEvent; |
18
|
|
|
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException; |
19
|
|
|
use Symfony\Component\HttpKernel\HttpKernelInterface; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* This listener handles Accept header format negotiations. |
23
|
|
|
* |
24
|
|
|
* @author Lukas Kahwe Smith <[email protected]> |
25
|
|
|
* |
26
|
|
|
* @internal |
27
|
|
|
*/ |
28
|
|
|
class FormatListener |
29
|
|
|
{ |
30
|
|
|
private $formatNegotiator; |
31
|
|
|
|
32
|
15 |
|
public function __construct(FormatNegotiator $formatNegotiator) |
33
|
|
|
{ |
34
|
15 |
|
$this->formatNegotiator = $formatNegotiator; |
35
|
15 |
|
} |
36
|
|
|
|
37
|
15 |
|
public function onKernelRequest(RequestEvent $event): void |
38
|
|
|
{ |
39
|
15 |
|
$request = $event->getRequest(); |
40
|
|
|
|
41
|
15 |
|
if (!$request->attributes->get(FOSRestBundle::ZONE_ATTRIBUTE, true)) { |
42
|
1 |
|
return; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
try { |
46
|
14 |
|
$format = $request->getRequestFormat(null); |
47
|
14 |
|
if (null === $format) { |
48
|
11 |
|
$accept = $this->formatNegotiator->getBest(''); |
49
|
11 |
|
if (null !== $accept && 0.0 < $accept->getQuality()) { |
50
|
10 |
|
$format = $request->getFormat($accept->getValue()); |
51
|
10 |
|
if (null !== $format) { |
52
|
10 |
|
$request->attributes->set('media_type', $accept->getValue()); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
14 |
|
if (null === $format) { |
58
|
1 |
|
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) { |
59
|
1 |
|
throw new NotAcceptableHttpException('No matching accepted Response format could be determined'); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return; |
63
|
|
|
} |
64
|
|
|
|
65
|
13 |
|
$request->setRequestFormat($format); |
66
|
1 |
|
} catch (StopFormatListenerException $e) { |
67
|
|
|
// nothing to do |
68
|
|
|
} |
69
|
13 |
|
} |
70
|
|
|
} |
71
|
|
|
|