Passed
Push — master ( 385b06...f80f2a )
by Roeland
13:28 queued 11s
created

CompressionMiddleware::afterController()   B

Complexity

Conditions 7
Paths 18

Size

Total Lines 32
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 16
c 2
b 0
f 0
nc 18
nop 3
dl 0
loc 32
rs 8.8333
1
<?php
2
3
declare(strict_types=1);
4
/**
5
 * @copyright Copyright (c) 2020, Roeland Jago Douma <[email protected]>
6
 *
7
 * @author Roeland Jago Douma <[email protected]>
8
 *
9
 * @license GNU AGPL version 3 or any later version
10
 *
11
 * This program is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU Affero General Public License as
13
 * published by the Free Software Foundation, either version 3 of the
14
 * License, or (at your option) any later version.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU Affero General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Affero General Public License
22
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23
 *
24
 */
25
26
namespace OC\AppFramework\Middleware;
27
28
use OC\AppFramework\OCS\BaseResponse;
29
use OCP\AppFramework\Http;
30
use OCP\AppFramework\Http\JSONResponse;
31
use OCP\AppFramework\Http\Response;
32
use OCP\AppFramework\Http\TemplateResponse;
33
use OCP\AppFramework\Middleware;
34
use OCP\IRequest;
35
36
class CompressionMiddleware extends Middleware {
37
38
	/** @var bool */
39
	private $useGZip;
40
41
	/** @var IRequest */
42
	private $request;
43
44
	public function __construct(IRequest $request) {
45
		$this->request = $request;
46
		$this->useGZip = false;
47
	}
48
49
	public function afterController($controller, $methodName, Response $response) {
50
		// By default we do not gzip
51
		$allowGzip = false;
52
53
		// Only return gzipped content for 200 responses
54
		if ($response->getStatus() !== Http::STATUS_OK) {
55
			return $response;
56
		}
57
58
		// Check if we are even asked for gzip
59
		$header = $this->request->getHeader('Accept-Encoding');
60
		if (strpos($header, 'gzip') === false) {
61
			return $response;
62
		}
63
64
		// We only allow gzip in some cases
65
		if ($response instanceof BaseResponse) {
66
			$allowGzip = true;
67
		}
68
		if ($response instanceof JSONResponse) {
69
			$allowGzip = true;
70
		}
71
		if ($response instanceof TemplateResponse) {
72
			$allowGzip = true;
73
		}
74
75
		if ($allowGzip) {
76
			$this->useGZip = true;
77
			$response->addHeader('Content-Encoding', 'gzip');
78
		}
79
80
		return $response;
81
	}
82
83
	public function beforeOutput($controller, $methodName, $output) {
84
		if (!$this->useGZip) {
85
			return $output;
86
		}
87
88
		return gzencode($output);
89
	}
90
}
91