Completed
Pull Request — stable9 (#52)
by Olivier
09:56
created

HttpError::getHttpStatusCode()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 8
cts 8
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 4
nop 1
crap 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