Passed
Push — master ( b17796...6374c3 )
by Roeland
10:46 queued 11s
created

CompressionMiddleware::afterController()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 29
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 14
c 1
b 0
f 0
nc 10
nop 3
dl 0
loc 29
rs 9.2222
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\Middleware;
33
use OCP\IRequest;
34
35
class CompressionMiddleware extends Middleware {
36
37
	/** @var bool */
38
	private $useGZip;
39
40
	/** @var IRequest */
41
	private $request;
42
43
	public function __construct(IRequest $request) {
44
		$this->request = $request;
45
		$this->useGZip = false;
46
	}
47
48
	public function afterController($controller, $methodName, Response $response) {
49
		// By default we do not gzip
50
		$allowGzip = false;
51
52
		// Only return gzipped content for 200 responses
53
		if ($response->getStatus() !== Http::STATUS_OK) {
54
			return $response;
55
		}
56
57
		// Check if we are even asked for gzip
58
		$header = $this->request->getHeader('Accept-Encoding');
59
		if (strpos($header, 'gzip') === false) {
60
			return $response;
61
		}
62
63
		// We only allow gzip in some cases
64
		if ($response instanceof BaseResponse) {
65
			$allowGzip = true;
66
		}
67
		if ($response instanceof JSONResponse) {
68
			$allowGzip = true;
69
		}
70
71
		if ($allowGzip) {
72
			$this->useGZip = true;
73
			$response->addHeader('Content-Encoding', 'gzip');
74
		}
75
76
		return $response;
77
	}
78
79
	public function beforeOutput($controller, $methodName, $output) {
80
		if (!$this->useGZip) {
81
			return $output;
82
		}
83
84
		return gzencode($output);
85
	}
86
}
87