OCSEndPoint   B
last analyzed

Complexity

Total Complexity 48

Size/Duplication

Total Lines 348
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 97.16%

Importance

Changes 0
Metric Value
wmc 48
lcom 1
cbo 3
dl 0
loc 348
ccs 137
cts 141
cp 0.9716
rs 8.5599
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 21 1
A getFilter() 0 3 1
B readParameters() 0 27 10
A getDefault() 0 5 1
C get() 0 62 15
B generateHeaders() 0 26 6
B getPreview() 0 50 7
A getPreviewFromPath() 0 10 1
A getPreviewPathFromMimeType() 0 8 2
A getPreviewLink() 0 13 4

How to fix   Complexity   

Complex Class

Complex classes like OCSEndPoint often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use OCSEndPoint, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @author Joas Schilling <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2016, ownCloud, Inc.
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
namespace OCA\Activity\Controller;
23
24
use OC\Files\View;
25
use OCA\Activity\Data;
26
use OCA\Activity\Exception\InvalidFilterException;
27
use OCA\Activity\GroupHelper;
28
use OCA\Activity\UserSettings;
29
use OCA\Activity\ViewInfoCache;
30
use OCP\AppFramework\Http;
31
use OCP\Files\FileInfo;
32
use OCP\Files\IMimeTypeDetector;
33
use OCP\IPreview;
34
use OCP\IRequest;
35
use OCP\IURLGenerator;
36
use OCP\IUser;
37
use OCP\IUserSession;
38
39
class OCSEndPoint {
40
41
	/** @var string */
42
	protected $filter;
43
44
	/** @var int */
45
	protected $since;
46
47
	/** @var int */
48
	protected $limit;
49
50
	/** @var string */
51
	protected $sort;
52
53
	/** @var string */
54
	protected $objectType;
55
56
	/** @var int */
57
	protected $objectId;
58
59
	/** @var string */
60
	protected $user;
61
62
	/** @var bool */
63
	protected $loadPreviews;
64
65
	/** @var Data */
66
	protected $data;
67
68
	/** @var GroupHelper */
69
	protected $helper;
70
71
	/** @var UserSettings */
72
	protected $settings;
73
74
	/** @var IRequest */
75
	protected $request;
76
77
	/** @var IURLGenerator */
78
	protected $urlGenerator;
79
80
	/** @var IUserSession */
81
	protected $userSession;
82
83
	/** @var IPreview */
84
	protected $preview;
85
86
	/** @var IMimeTypeDetector */
87
	protected $mimeTypeDetector;
88
89
	/** @var View */
90
	protected $view;
91
92
	/** @var ViewInfoCache */
93
	protected $infoCache;
94
95
	/**
96
	 * OCSEndPoint constructor.
97
	 *
98
	 * @param Data $data
99
	 * @param GroupHelper $helper
100
	 * @param UserSettings $settings
101
	 * @param IRequest $request
102
	 * @param IURLGenerator $urlGenerator
103
	 * @param IUserSession $userSession
104
	 * @param IPreview $preview
105
	 * @param IMimeTypeDetector $mimeTypeDetector
106
	 * @param View $view
107
	 * @param ViewInfoCache $infoCache
108
	 */
109 61
	public function __construct(Data $data,
110
								GroupHelper $helper,
111
								UserSettings $settings,
112
								IRequest $request,
113
								IURLGenerator $urlGenerator,
114
								IUserSession $userSession,
115
								IPreview $preview,
116
								IMimeTypeDetector $mimeTypeDetector,
117
								View $view,
118
								ViewInfoCache $infoCache) {
119 61
		$this->data = $data;
120 61
		$this->helper = $helper;
121 61
		$this->settings = $settings;
122 61
		$this->request = $request;
123 61
		$this->urlGenerator = $urlGenerator;
124 61
		$this->userSession = $userSession;
125 61
		$this->preview = $preview;
126 61
		$this->mimeTypeDetector = $mimeTypeDetector;
127 61
		$this->view = $view;
128 61
		$this->infoCache = $infoCache;
129 61
	}
130
131
	/**
132
	 * @param array $parameters
133
	 * @throws InvalidFilterException when the filter is invalid
134
	 * @throws \OutOfBoundsException when no user is given
135
	 */
136 23
	protected function readParameters(array $parameters) {
137 23
		$this->filter = isset($parameters['filter']) && \is_string($parameters['filter']) ? (string) $parameters['filter'] : 'all';
138 23
		if ($this->filter !== $this->data->validateFilter($this->filter)) {
139 2
			throw new InvalidFilterException();
140
		}
141 21
		$this->since = (int) $this->request->getParam('since', 0);
142 21
		$this->limit = (int) $this->request->getParam('limit', 50);
143 21
		$this->loadPreviews = $this->request->getParam('previews', 'false') === 'true';
144 21
		$this->objectType = (string) $this->request->getParam('object_type', '');
145 21
		$this->objectId = (int) $this->request->getParam('object_id', 0);
146 21
		$this->sort = (string) $this->request->getParam('sort', '');
147 21
		$this->sort = \in_array($this->sort, ['asc', 'desc']) ? $this->sort : 'desc';
148
149 21
		if ($this->objectType !== '' && $this->objectId === 0 || $this->objectType === '' && $this->objectId !== 0) {
150
			// Only allowed together
151 2
			$this->objectType = '';
152 2
			$this->objectId = 0;
153
		}
154
155 21
		$user = $this->userSession->getUser();
156 21
		if ($user instanceof IUser) {
0 ignored issues
show
Bug introduced by
The class OCP\IUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
157 20
			$this->user = $user->getUID();
158
		} else {
159
			// No user logged in
160 1
			throw new \OutOfBoundsException();
161
		}
162 20
	}
163
164
	/**
165
	 * @param array $parameters
166
	 * @return \OC_OCS_Result
167
	 */
168 3
	public function getDefault(array $parameters) {
169 3
		return $this->get(\array_merge($parameters, [
170 3
			'filter' => 'all',
171
		]));
172
	}
173
174
	/**
175
	 * @param array $parameters
176
	 * @return \OC_OCS_Result
177
	 */
178 3
	public function getFilter(array $parameters) {
179 3
		return $this->get($parameters);
180
	}
181
182
	/**
183
	 * @param array $parameters
184
	 * @return \OC_OCS_Result
185
	 */
186 9
	protected function get(array $parameters) {
187
		try {
188 9
			$this->readParameters($parameters);
189 2
		} catch (InvalidFilterException $e) {
190 1
			return new \OC_OCS_Result(null, Http::STATUS_NOT_FOUND);
191 1
		} catch (\OutOfBoundsException $e) {
192 1
			return new \OC_OCS_Result(null, Http::STATUS_FORBIDDEN);
193
		}
194
195
		try {
196 7
			$response = $this->data->get(
197 7
				$this->helper,
198 7
				$this->settings,
199 7
				$this->user,
200
201 7
				$this->since,
202 7
				$this->limit,
203 7
				$this->sort,
204
205 7
				$this->filter,
206 7
				$this->objectType,
207 7
				$this->objectId
208
			);
209 2
		} catch (\OutOfBoundsException $e) {
210
			// Invalid since argument
211 1
			return new \OC_OCS_Result(null, Http::STATUS_FORBIDDEN);
212 1
		} catch (\BadMethodCallException $e) {
213
			// No activity settings enabled
214 1
			return new \OC_OCS_Result(null, Http::STATUS_NO_CONTENT);
215
		}
216
217 5
		$headers = $this->generateHeaders($response['headers'], $response['has_more']);
218 5
		if (empty($response['data'])) {
219 1
			return new \OC_OCS_Result([], Http::STATUS_NOT_MODIFIED, null, $headers);
220
		}
221
222 4
		$preparedActivities = [];
223 4
		foreach ($response['data'] as $activity) {
224 4
			$activity['datetime'] = \date('c', $activity['timestamp']);
225 4
			unset($activity['timestamp']);
226
227 4
			if ($this->loadPreviews) {
228 3
				$activity['previews'] = [];
229 3
				if ($activity['object_type'] === 'files' && !empty($activity['files'])) {
230 1
					foreach ($activity['files'] as $objectId => $objectName) {
0 ignored issues
show
Bug introduced by
The expression $activity['files'] of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
231 1
						if (((int) $objectId) === 0 || $objectName === '') {
232
							// No file, no preview
233 1
							continue;
234
						}
235
236 1
						$activity['previews'][] = $this->getPreview($activity['affecteduser'], (int) $objectId, $objectName);
237
					}
238 2
				} elseif ($activity['object_type'] === 'files' && $activity['object_id']) {
239 1
					$activity['previews'][] = $this->getPreview($activity['affecteduser'], (int) $activity['object_id'], $activity['object_name']);
240
				}
241
			}
242
243 4
			$preparedActivities[] = $activity;
244
		}
245
246 4
		return new \OC_OCS_Result($preparedActivities, 100, null, $headers);
247
	}
248
249
	/**
250
	 * @param array $headers
251
	 * @param bool $hasMoreActivities
252
	 * @return array
253
	 */
254 4
	protected function generateHeaders(array $headers, $hasMoreActivities) {
255 4
		if ($hasMoreActivities && isset($headers['X-Activity-Last-Given'])) {
256
			// Set the "Link" header for the next page
257
			$nextPageParameters = [
258 3
				'since' => $headers['X-Activity-Last-Given'],
259 3
				'limit' => $this->limit,
260 3
				'sort' => $this->sort,
261
			];
262 3
			if ($this->objectType && $this->objectId) {
263 1
				$nextPageParameters['object_type'] = $this->objectType;
264 1
				$nextPageParameters['object_id'] = $this->objectId;
265
			}
266 3
			if ($this->request->getParam('format') !== null) {
267 1
				$nextPageParameters['format'] = $this->request->getParam('format');
268
			}
269
270 3
			$nextPage = $this->request->getServerProtocol(); # http
271 3
			$nextPage .= '://' . $this->request->getServerHost(); # localhost
272 3
			$nextPage .= $this->request->getScriptName(); # /ocs/v2.php
273 3
			$nextPage .= $this->request->getPathInfo(); # /apps/activity/api/v2/activity
274 3
			$nextPage .= '?' . \http_build_query($nextPageParameters);
275 3
			$headers['Link'] = '<' . $nextPage . '>; rel="next"';
276
		}
277
278 4
		return $headers;
279
	}
280
281
	/**
282
	 * @param string $owner
283
	 * @param int $fileId
284
	 * @param string $filePath
285
	 * @return array
286
	 */
287 7
	protected function getPreview($owner, $fileId, $filePath) {
288 7
		$info = $this->infoCache->getInfoById($owner, $fileId, $filePath);
289
290 7
		if (!$info['exists'] || $info['view'] !== '') {
291 3
			return $this->getPreviewFromPath($filePath, $info);
292
		}
293
294
		$preview = [
295 4
			'link'			=> $this->getPreviewLink($info['path'], $info['is_dir'], $info['view']),
296 4
			'source'		=> '',
297
			'isMimeTypeIcon' => true,
298
		];
299
300
		// show a preview image if the file still exists
301 4
		if ($info['is_dir']) {
302 1
			$preview['source'] = $this->getPreviewPathFromMimeType('dir');
303
		} else {
304 3
			$this->view->chroot('/' . $owner . '/files');
305 3
			$fileInfo = $this->view->getFileInfo($info['path']);
306 3
			if (!($fileInfo instanceof FileInfo)) {
0 ignored issues
show
Bug introduced by
The class OCP\Files\FileInfo does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
307 1
				$pathPreview = $this->getPreviewFromPath($filePath, $info);
308 1
				$preview['source'] = $pathPreview['source'];
309 2
			} elseif ($this->preview->isAvailable($fileInfo)) {
310 1
				$preview['isMimeTypeIcon'] = false;
311 1
				if (\version_compare(\implode('.', \OCP\Util::getVersion()), '10.0.9', '>=')) {
312 1
					$query = \http_build_query([
313 1
						'preview' => 1,
314 1
						'c' => $this->view->getETag($info['path']),
315 1
						'x' => 150,
316 1
						'y' => 150
317 1
					], '', '&');
318
319 1
					$preview['source'] = $this->urlGenerator->linkTo('', 'remote.php')
320 1
						. '/dav/files/' . \rawurlencode($this->user) . \OCP\Util::encodePath($filePath)
321 1
						. "?$query";
322
				} else {
323
					$preview['source'] = $this->urlGenerator->linkToRoute('core_ajax_preview', [
324
						'file' => $info['path'],
325
						'c' => $this->view->getETag($info['path']),
326
						'x' => 150,
327 1
						'y' => 150,
328
					]);
329
				}
330
			} else {
331 1
				$preview['source'] = $this->getPreviewPathFromMimeType($fileInfo->getMimetype());
332
			}
333
		}
334
335 4
		return $preview;
336
	}
337
338
	/**
339
	 * @param string $filePath
340
	 * @param array $info
341
	 * @return array
342
	 */
343 3
	protected function getPreviewFromPath($filePath, $info) {
344 3
		$mimeType = $this->mimeTypeDetector->detectPath($filePath);
345
		$preview = [
346 3
			'link'			=> $this->getPreviewLink($info['path'], $info['is_dir'], $info['view']),
347 3
			'source'		=> $this->getPreviewPathFromMimeType($mimeType),
348
			'isMimeTypeIcon' => true,
349
		];
350
351 3
		return $preview;
352
	}
353
354
	/**
355
	 * @param string $mimeType
356
	 * @return string
357
	 */
358 3
	protected function getPreviewPathFromMimeType($mimeType) {
359 3
		$mimeTypeIcon = $this->mimeTypeDetector->mimeTypeIcon($mimeType);
360 3
		if (\substr($mimeTypeIcon, -4) === '.png') {
361 1
			$mimeTypeIcon = \substr($mimeTypeIcon, 0, -4) . '.svg';
362
		}
363
364 3
		return $mimeTypeIcon;
365
	}
366
367
	/**
368
	 * @param string $path
369
	 * @param bool $isDir
370
	 * @param string $view
371
	 * @return string
372
	 */
373 6
	protected function getPreviewLink($path, $isDir, $view) {
374
		$params = [
375 6
			'dir' => $path,
376
		];
377 6
		if (!$isDir) {
378 3
			$params['dir'] = (\substr_count($path, '/') === 1) ? '/' : \dirname($path);
379 3
			$params['scrollto'] = \basename($path);
380
		}
381 6
		if ($view !== '') {
382 2
			$params['view'] = $view;
383
		}
384 6
		return $this->urlGenerator->linkToRoute('files.view.index', $params);
385
	}
386
}
387