Completed
Push — master ( 3dda54...befd6a )
by Michael
02:11
created

Application::setErrorHeader()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 7.6055

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 26
ccs 9
cts 17
cp 0.5294
rs 8.439
cc 5
eloc 15
nc 5
nop 1
crap 7.6055
1
<?php
2
3
namespace Stats;
4
5
use Joomla\Application\AbstractWebApplication;
6
7
/**
8
 * Web application for the stats server
9
 *
10
 * @since  1.0
11
 */
12
class Application extends AbstractWebApplication
13
{
14
	/**
15
	 * Response mime type.
16
	 *
17
	 * @var    string
18
	 * @since  1.0
19
	 */
20
	public $mimeType = 'application/json';
21
22
	/**
23
	 * Application router.
24
	 *
25
	 * @var    Router
26
	 * @since  1.0
27
	 */
28
	private $router;
29
30
	/**
31
	 * Method to run the application routines.
32
	 *
33
	 * @return  void
34
	 *
35
	 * @since   1.0
36
	 */
37 2
	public function doExecute()
38
	{
39
		try
40
		{
41 2
			$this->router->getController($this->get('uri.route'))->execute();
42
		}
43 2
		catch (\Exception $e)
44
		{
45
			// Log the error for reference
46 1
			$this->getLogger()->error(
47 1
				sprintf('Uncaught Exception of type %s caught.', get_class($e)),
48 1
				['exception' => $e]
49 1
			);
50
51 1
			$this->setErrorHeader($e);
52
53
			$data = [
54 1
				'error'   => true,
55 1
				'message' => $e->getMessage(),
56 1
			];
57
58 1
			$this->setBody(json_encode($data));
59
		}
60 2
	}
61
62
	/**
63
	 * Set the HTTP Response Header for error conditions.
64
	 *
65
	 * @param   \Exception  $exception  The Exception object to process.
66
	 *
67
	 * @return  void
68
	 *
69
	 * @since   1.0
70
	 */
71 1
	private function setErrorHeader(\Exception $exception)
72
	{
73 1
		switch ($exception->getCode())
74
		{
75 1
			case 401:
76
				$this->setHeader('HTTP/1.1 401 Unauthorized', 401, true);
77
78
				break;
79
80 1
			case 403:
81
				$this->setHeader('HTTP/1.1 403 Forbidden', 403, true);
82
83
				break;
84
85 1
			case 404:
86 1
				$this->setHeader('HTTP/1.1 404 Not Found', 404, true);
87
88 1
				break;
89
90
			case 500:
91
			default:
92
				$this->setHeader('HTTP/1.1 500 Internal Server Error', 500, true);
93
94
				break;
95 1
		}
96 1
	}
97
98
	/**
99
	 * Set the application's router.
100
	 *
101
	 * @param   Router  $router  Router object to set.
102
	 *
103
	 * @return  $this
104
	 *
105
	 * @since   1.0
106
	 */
107 1
	public function setRouter(Router $router)
108
	{
109 1
		$this->router = $router;
110
111 1
		return $this;
112
	}
113
}
114