Completed
Push — master ( 126a82...e45248 )
by Morris
11:37
created

ZipResponse::callback()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 1
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
/**
5
 * @copyright Copyright (c) 2018 Roeland Jago Douma <[email protected]>
6
 *
7
 * @author Jakob Sack <[email protected]>
8
 * @author Roeland Jago Douma <[email protected]>
9
 *
10
 * @license AGPL-3.0
11
 *
12
 * This code is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License, version 3,
14
 * as published by the Free Software Foundation.
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, version 3,
22
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
23
 *
24
 */
25
26
namespace OCP\AppFramework\Http;
27
28
use OCP\IRequest;
29
use OC\Streamer;
30
31
/**
32
 * Public library to send several files in one zip archive.
33
 *
34
 * @since 15.0.0
35
 */
36
class ZipResponse extends Response implements ICallbackResponse {
37
	/** @var resource[] Files to be added to the zip response */
38
	private $resources;
39
	/** @var string Filename that the zip file should have */
40
	private $name;
41
	private $request;
42
43
	/**
44
	 * @since 15.0.0
45
	 */
46
	public function __construct(IRequest $request, string $name = 'output') {
47
		$this->name = $name;
48
		$this->request = $request;
49
	}
50
51
	/**
52
	 * @since 15.0.0
53
	 */
54
	public function addResource($r, string $internalName, int $size, int $time = -1) {
55
		if (!\is_resource($r)) {
56
			throw new \InvalidArgumentException('No resource provided');
57
		}
58
59
		$this->resources[] = [
60
			'resource' => $r,
61
			'internalName' => $internalName,
62
			'size' => $size,
63
			'time' => $time,
64
		];
65
	}
66
67
	/**
68
	 * @since 15.0.0
69
	 */
70
	public function callback(IOutput $output) {
71
		$size = 0;
72
		$files = count($this->resources);
73
74
		foreach ($this->resources as $resource) {
75
			$size += $resource['size'];
76
		}
77
78
		$zip = new Streamer($this->request, $size, $files);
79
		$zip->sendHeaders($this->name);
80
81
		foreach ($this->resources as $resource) {
82
			$zip->addFileFromStream($resource['resource'], $resource['internalName'], $resource['size'], $resource['time']);
83
		}
84
85
		$zip->finalize();
86
	}
87
}
88