Completed
Push — stable9 ( ab68a4...eef0b3 )
by Olivier
10s
created

HttpError   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 0
dl 0
loc 61
ccs 21
cts 21
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A jsonError() 0 12 1
A htmlError() 0 12 1
A getHttpStatusCode() 0 13 4
1
<?php
2
/**
3
 * ownCloud - galleryplus
4
 *
5
 * This file is licensed under the Affero General Public License version 3 or
6
 * later. See the COPYING file.
7
 *
8
 * @author Bernhard Posselt <[email protected]>
9
 * @author Olivier Paroz <[email protected]>
10
 *
11
 * @copyright Bernhard Posselt 2014-2015
12
 * @copyright Olivier Paroz 2014-2016
13
 */
14
15
namespace OCA\GalleryPlus\Controller;
16
17
use Exception;
18
19
use OCP\IURLGenerator;
20
21
use OCP\AppFramework\Http;
22
use OCP\AppFramework\Http\JSONResponse;
23
use OCP\AppFramework\Http\RedirectResponse;
24
25
use OCA\GalleryPlus\Environment\NotFoundEnvException;
26
use OCA\GalleryPlus\Service\NotFoundServiceException;
27
use OCA\GalleryPlus\Service\ForbiddenServiceException;
28
29
/**
30
 * Our classes extend both Controller and ApiController, so we need to use
31
 * traits to add some common methods
32
 *
33
 * @package OCA\GalleryPlus\Controller
34
 */
35
trait HttpError {
36
37
	/**
38
	 * @param \Exception $exception
39
	 *
40
	 * @return JSONResponse
41
	 */
42 12
	public function jsonError(Exception $exception) {
43 12
		$message = $exception->getMessage();
44 12
		$code = $this->getHttpStatusCode($exception);
45
46 12
		return new JSONResponse(
47
			[
48 12
				'message' => $message . ' (' . $code . ')',
49
				'success' => false
50
			],
51
			$code
52
		);
53
	}
54
55
	/**
56
	 * @param IURLGenerator $urlGenerator
57
	 * @param string $appName
58
	 * @param \Exception $exception
59
	 *
60
	 * @return RedirectResponse
61
	 */
62 6
	public function htmlError($urlGenerator, $appName, Exception $exception) {
63 6
		$message = $exception->getMessage();
64 6
		$code = $this->getHttpStatusCode($exception);
65 6
		$url = $urlGenerator->linkToRoute(
66 6
			$appName . '.page.error_page', ['code' => $code]
67
		);
68
69 6
		$response = new RedirectResponse($url);
70 6
		$response->addCookie('galleryErrorMessage', $message);
71
72 6
		return $response;
73
	}
74
75
	/**
76
	 * Returns an error array
77
	 *
78
	 * @param $exception
79
	 *
80
	 * @return array<null|int|string>
81
	 */
82 33
	public function getHttpStatusCode($exception) {
83 33
		$code = Http::STATUS_INTERNAL_SERVER_ERROR;
84 33
		if ($exception instanceof NotFoundServiceException
85 33
			|| $exception instanceof NotFoundEnvException
86
		) {
87 13
			$code = Http::STATUS_NOT_FOUND;
88
		}
89 33
		if ($exception instanceof ForbiddenServiceException) {
90 3
			$code = Http::STATUS_FORBIDDEN;
91
		}
92
93 33
		return $code;
94
	}
95
}
96