Completed
Pull Request — master (#2092)
by Joas
08:22 queued 01:00
created

Helper::getFavoriteFilePaths()   C

Complexity

Conditions 7
Paths 10

Size

Total Lines 36
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 22
nc 10
nop 1
dl 0
loc 36
rs 6.7272
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Joas Schilling <[email protected]>
6
 *
7
 * @license AGPL-3.0
8
 *
9
 * This code is free software: you can redistribute it and/or modify
10
 * it under the terms of the GNU Affero General Public License, version 3,
11
 * as published by the Free Software Foundation.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
 * GNU Affero General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Affero General Public License, version 3,
19
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
20
 *
21
 */
22
23
namespace OCA\Files\Activity;
24
25
use OCP\Files\Folder;
26
use OCP\ITagManager;
27
28
class Helper {
29
	/** If a user has a lot of favorites the query might get too slow and long */
30
	const FAVORITE_LIMIT = 50;
31
32
	/** @var ITagManager */
33
	protected $tagManager;
34
35
	/**
36
	 * @param ITagManager $tagManager
37
	 */
38
	public function __construct(ITagManager $tagManager) {
39
		$this->tagManager = $tagManager;
40
	}
41
42
	/**
43
	 * Returns an array with the favorites
44
	 *
45
	 * @param string $user
46
	 * @return array
47
	 * @throws \RuntimeException when too many or no favorites where found
48
	 */
49
	public function getFavoriteFilePaths($user) {
50
		$tags = $this->tagManager->load('files', [], false, $user);
51
		$favorites = $tags->getFavorites();
52
53
		if (empty($favorites)) {
54
			throw new \RuntimeException('No favorites', 1);
55
		} else if (isset($favorites[self::FAVORITE_LIMIT])) {
56
			throw new \RuntimeException('Too many favorites', 2);
57
		}
58
59
		// Can not DI because the user is not known on instantiation
60
		$rootFolder = \OC::$server->getUserFolder($user);
61
		$folders = $items = [];
62
		foreach ($favorites as $favorite) {
63
			$nodes = $rootFolder->getById($favorite);
64
			if (!empty($nodes)) {
65
				/** @var \OCP\Files\Node $node */
66
				$node = array_shift($nodes);
67
				$path = substr($node->getPath(), strlen($user . '/files/'));
68
69
				$items[] = $path;
70
				if ($node instanceof Folder) {
71
					$folders[] = $path;
72
				}
73
			}
74
		}
75
76
		if (empty($items)) {
77
			throw new \RuntimeException('No favorites', 1);
78
		}
79
80
		return [
81
			'items' => $items,
82
			'folders' => $folders,
83
		];
84
	}
85
}
86