blob: 75aa4f10f01c99f22f4c44e718d111341db46cd7 (
plain)
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
105
106
107
108
|
<?php
namespace Jasny\Controller;
/**
* Controller methods to negotiate content
*/
trait ContentNegotiation
{
/**
* Get request, set for controller
*
* @return ServerRequestInterface
*/
abstract public function getRequest();
/**
* Pick best content type
*
* @param array $priorities
* @return string
*/
public function negotiateContentType(array $priorities)
{
return $this->negotiate($priorities);
}
/**
* Pick best language
*
* @param array $priorities
* @return string
*/
public function negotiateLanguage(array $priorities)
{
return $this->negotiate($priorities, 'language');
}
/**
* Pick best encoding
*
* @param array $priorities
* @return string
*/
public function negotiateEncoding(array $priorities)
{
return $this->negotiate($priorities, 'encoding');
}
/**
* Pick best charset
*
* @param array $priorities
* @return string
*/
public function negotiateCharset(array $priorities)
{
return $this->negotiate($priorities, 'charset');
}
/**
* Generalize negotiation
*
* @param array $priorities
* @param string $type Negotiator type
* @return string
*/
protected function negotiate(array $priorities, $type = '')
{
$header = 'Accept';
if ($type) {
$header .= '-' . ucfirst($type);
}
$header = $this->getRequest()->getHeader($header);
$header = join(', ', $header);
$negotiator = $this->getNegotiator($type);
$chosen = $negotiator->getBest($header, $priorities);
return $chosen ? $chosen->getType() : '';
}
/**
* Get negotiation library instance
*
* @param string $type Negotiator type
* @return Negotiation\AbstractNegotiator
*/
protected function getNegotiator($type = '')
{
$class = $this->getNegotiatorName($type);
return new $class();
}
/**
* Get negotiator name
*
* @param string $type
* @return string
*/
protected function getNegotiatorName($type = '')
{
return 'Negotiation\\' . ucfirst($type) . 'Negotiator';
}
}
|