/
FormatListener.php
104 lines (87 loc) · 3.02 KB
/
FormatListener.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?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 Symfony\Component\HttpKernel\Event\FilterControllerEvent,
Symfony\Component\Serializer\SerializerInterface,
Symfony\Component\HttpKernel\Exception\HttpException,
Symfony\Component\HttpKernel\HttpKernelInterface;
use FOS\RestBundle\Response\Codes,
FOS\RestBundle\Util\FormatNegotiatorInterface;
/**
* This listener handles Accept header format negotiations.
*
* @author Lukas Kahwe Smith <smith@pooteeweet.org>
*/
class FormatListener
{
/**
* @var FormatNegotiatorInterface
*/
private $formatNegotiator;
/**
* @var array Ordered array of formats (highest priority first)
*/
private $defaultPriorities;
/**
* @var string fallback format name
*/
private $fallbackFormat;
/**
* @var Boolean if to consider the extension last or first
*/
private $preferExtension;
/**
* Initialize FormatListener.
*
* @param FormatNegotiatorInterface $formatNegotiator The content negotiator service to use
* @param string $fallbackFormat Default fallback format
* @param array $defaultPriorities Ordered array of formats (highest priority first)
* @param Boolean $preferExtension If to consider the extension last or first
*/
public function __construct(FormatNegotiatorInterface $formatNegotiator, $fallbackFormat, array $defaultPriorities = array(), $preferExtension = false)
{
$this->formatNegotiator = $formatNegotiator;
$this->defaultPriorities = $defaultPriorities;
$this->fallbackFormat = $fallbackFormat;
$this->preferExtension = $preferExtension;
}
/**
* Determines and sets the Request format
*
* @param GetResponseEvent $event The event
*/
public function onKernelController(FilterControllerEvent $event)
{
$request = $event->getRequest();
/*
// TODO get priorities from the controller action
$action = $request->attributes->get('_controller');
$controller = $event->getController();
$priorities =
*/
if (empty($priorities)) {
$priorities = $this->defaultPriorities;
}
$format = null;
if (!empty($priorities)) {
$format = $this->formatNegotiator->getBestFormat($request, $priorities, $this->preferExtension);
}
if (null === $format) {
$format = $this->fallbackFormat;
}
if (null === $format) {
if ($event->getRequestType() === HttpKernelInterface::MASTER_REQUEST) {
throw new HttpException(Codes::HTTP_NOT_ACCEPTABLE, "No matching accepted Response format could be determined");
}
return;
}
$request->setRequestFormat($format);
}
}