|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Koded\Framework\Middleware; |
|
4
|
|
|
|
|
5
|
|
|
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface}; |
|
6
|
|
|
use Psr\Http\Server\{MiddlewareInterface, RequestHandlerInterface}; |
|
7
|
|
|
use function gzencode; |
|
8
|
|
|
use function Koded\Http\create_stream; |
|
9
|
|
|
use function str_contains; |
|
10
|
|
|
|
|
11
|
|
|
class GzipMiddleware implements MiddlewareInterface |
|
12
|
|
|
{ |
|
13
|
|
|
private const ACCEPT_ENCODING = 'Accept-Encoding'; |
|
14
|
|
|
private const CONTENT_ENCODING = 'Content-Encoding'; |
|
15
|
|
|
|
|
16
|
3 |
|
public function process( |
|
17
|
|
|
ServerRequestInterface $request, |
|
18
|
|
|
RequestHandlerInterface $handler): ResponseInterface |
|
19
|
|
|
{ |
|
20
|
3 |
|
$response = $handler->handle($request); |
|
21
|
1 |
|
if ($response->hasHeader(self::CONTENT_ENCODING)) { |
|
22
|
|
|
return $response; |
|
23
|
|
|
} |
|
24
|
1 |
|
if (!$response->getBody()->getSize()) { |
|
|
|
|
|
|
25
|
1 |
|
return $response; |
|
26
|
|
|
} |
|
27
|
|
|
if (false === $this->isAcceptable($request->getHeaderLine(self::ACCEPT_ENCODING))) { |
|
28
|
|
|
return $response; |
|
29
|
|
|
} |
|
30
|
|
|
$response->getBody()->rewind(); |
|
31
|
|
|
return $response |
|
32
|
|
|
->withHeader(self::CONTENT_ENCODING, 'gzip') |
|
33
|
|
|
->withAddedHeader('Vary', self::ACCEPT_ENCODING) |
|
34
|
|
|
->withBody(create_stream( |
|
35
|
|
|
gzencode($response->getBody()->getContents(), 7), |
|
36
|
|
|
$response->getBody()->getMetadata('mode') |
|
|
|
|
|
|
37
|
|
|
)); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
private function isAcceptable(string $encoding): bool |
|
41
|
|
|
{ |
|
42
|
|
|
if (empty($encoding)) { |
|
43
|
|
|
return false; |
|
44
|
|
|
} |
|
45
|
|
|
if (str_contains($encoding, 'gzip')) { |
|
46
|
|
|
return true; |
|
47
|
|
|
} |
|
48
|
|
|
if (str_contains($encoding, '*')) { |
|
49
|
|
|
return true; |
|
50
|
|
|
} |
|
51
|
|
|
return false; |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
In PHP, under loose comparison (like
==, or!=, orswitchconditions), values of different types might be equal.For
integervalues, zero is a special case, in particular the following results might be unexpected: