kodeart /
koded
| 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 | 14 | public function process( |
|
| 17 | ServerRequestInterface $request, |
||
| 18 | RequestHandlerInterface $handler): ResponseInterface |
||
| 19 | { |
||
| 20 | 14 | $response = $handler->handle($request); |
|
| 21 | |||
| 22 | 12 | if ($response->hasHeader(self::CONTENT_ENCODING)) { |
|
| 23 | // Probably already encoded; move on |
||
| 24 | 3 | return $response; |
|
| 25 | } |
||
| 26 | 9 | if (empty($response->getBody()->getSize())) { |
|
| 27 | 4 | return $response; |
|
| 28 | } |
||
| 29 | 5 | if (false === $this->isAcceptable($request->getHeaderLine(self::ACCEPT_ENCODING))) { |
|
| 30 | 2 | return $response; |
|
| 31 | } |
||
| 32 | 3 | $response->getBody()->rewind(); |
|
| 33 | 3 | return $response |
|
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
Loading history...
|
|||
| 34 | 3 | ->withHeader(self::CONTENT_ENCODING, 'gzip') |
|
| 35 | 3 | ->withAddedHeader('Vary', self::ACCEPT_ENCODING) |
|
| 36 | 3 | ->withBody(create_stream( |
|
| 37 | 3 | gzencode($response->getBody()->getContents(), 7), |
|
| 38 | 3 | (string)$response->getBody()->getMetadata('mode') |
|
| 39 | 3 | )); |
|
| 40 | } |
||
| 41 | |||
| 42 | 5 | private function isAcceptable(string $encoding): bool |
|
| 43 | { |
||
| 44 | 5 | return match (true) { |
|
| 45 | // NOTE: most common first |
||
| 46 | 5 | empty($encoding) => false, |
|
| 47 | 5 | str_contains($encoding, 'gzip'), |
|
| 48 | 5 | str_contains($encoding, '*') => true, |
|
| 49 | 5 | default => false |
|
| 50 | 5 | }; |
|
| 51 | } |
||
| 52 | } |
||
| 53 |