1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Psr7Middlewares\Middleware; |
4
|
|
|
|
5
|
|
|
use Psr7Middlewares\Middleware; |
6
|
|
|
use Psr7Middlewares\Utils; |
7
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use Negotiation\EncodingNegotiator as Negotiator; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Middleware that returns the client preferred encoding. |
13
|
|
|
*/ |
14
|
|
|
class EncodingNegotiator |
15
|
|
|
{ |
16
|
|
|
use Utils\NegotiateTrait; |
17
|
|
|
|
18
|
|
|
const KEY = 'ENCODING'; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var array Available encodings |
22
|
|
|
*/ |
23
|
|
|
private $encodings = [ |
24
|
|
|
'gzip', |
25
|
|
|
'deflate', |
26
|
|
|
]; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Returns the encoding. |
30
|
|
|
* |
31
|
|
|
* @param ServerRequestInterface $request |
32
|
|
|
* |
33
|
|
|
* @return string|null |
34
|
|
|
*/ |
35
|
|
|
public static function getEncoding(ServerRequestInterface $request) |
36
|
|
|
{ |
37
|
|
|
return Middleware::getAttribute($request, self::KEY); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Constructor. Defines de available encodings. |
42
|
|
|
* |
43
|
|
|
* @param array $encodings |
44
|
|
|
*/ |
45
|
|
|
public function __construct(array $encodings = null) |
46
|
|
|
{ |
47
|
|
|
if ($encodings !== null) { |
48
|
|
|
$this->encodings($encodings); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Configure the available encodings. |
54
|
|
|
* |
55
|
|
|
* @param array $encodings |
56
|
|
|
* |
57
|
|
|
* @return self |
58
|
|
|
*/ |
59
|
|
|
public function encodings(array $encodings) |
60
|
|
|
{ |
61
|
|
|
$this->encodings = $encodings; |
62
|
|
|
|
63
|
|
|
return $this; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Execute the middleware. |
68
|
|
|
* |
69
|
|
|
* @param ServerRequestInterface $request |
70
|
|
|
* @param ResponseInterface $response |
71
|
|
|
* @param callable $next |
72
|
|
|
* |
73
|
|
|
* @return ResponseInterface |
74
|
|
|
*/ |
75
|
|
|
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
76
|
|
|
{ |
77
|
|
|
$encoding = $this->negotiateHeader($request->getHeaderLine('Accept-Encoding'), new Negotiator(), $this->encodings); |
78
|
|
|
|
79
|
|
|
$request = Middleware::setAttribute($request, self::KEY, $encoding); |
80
|
|
|
|
81
|
|
|
return $next($request, $response); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|