123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- <?php
- declare(strict_types=1);
- namespace OC\AppFramework\Middleware;
- use OC\AppFramework\OCS\BaseResponse;
- use OCP\AppFramework\Http;
- use OCP\AppFramework\Http\JSONResponse;
- use OCP\AppFramework\Http\Response;
- use OCP\AppFramework\Http\TemplateResponse;
- use OCP\AppFramework\Middleware;
- use OCP\IRequest;
- class CompressionMiddleware extends Middleware {
-
- private $useGZip;
-
- private $request;
- public function __construct(IRequest $request) {
- $this->request = $request;
- $this->useGZip = false;
- }
- public function afterController($controller, $methodName, Response $response) {
-
- $allowGzip = false;
-
- if ($response->getStatus() !== Http::STATUS_OK) {
- return $response;
- }
-
- $header = $this->request->getHeader('Accept-Encoding');
- if (!str_contains($header, 'gzip')) {
- return $response;
- }
-
- if ($response instanceof BaseResponse) {
- $allowGzip = true;
- }
- if ($response instanceof JSONResponse) {
- $allowGzip = true;
- }
- if ($response instanceof TemplateResponse) {
- $allowGzip = true;
- }
- if ($allowGzip) {
- $this->useGZip = true;
- $response->addHeader('Content-Encoding', 'gzip');
- }
- return $response;
- }
- public function beforeOutput($controller, $methodName, $output) {
- if (!$this->useGZip) {
- return $output;
- }
- return gzencode($output);
- }
- }
|