Completed
Push — master ( 77c306...84aad0 )
by Michael
02:51
created

DisplayControllerGet::execute()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 36
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 4

Importance

Changes 6
Bugs 1 Features 1
Metric Value
c 6
b 1
f 1
dl 0
loc 36
ccs 18
cts 18
cp 1
rs 8.5806
cc 4
eloc 16
nc 3
nop 0
crap 4
1
<?php
2
3
namespace Stats\Controllers;
4
5
use Doctrine\Common\Cache\Cache;
6
use Joomla\Controller\AbstractController;
7
use Stats\Views\Stats\StatsJsonView;
8
9
/**
10
 * Controller for displaying submitted statistics data.
11
 *
12
 * @method         \Stats\Application  getApplication()  Get the application object.
13
 * @property-read  \Stats\Application  $app              Application object
14
 *
15
 * @since          1.0
16
 */
17
class DisplayControllerGet extends AbstractController
18
{
19
	/**
20
	 * The cache handler.
21
	 *
22
	 * @var    Cache
23
	 * @since  1.0
24
	 */
25
	private $cache;
26
27
	/**
28
	 * JSON view for displaying the statistics.
29
	 *
30
	 * @var    StatsJsonView
31
	 * @since  1.0
32
	 */
33
	private $view;
34
35
	/**
36
	 * Constructor.
37
	 *
38
	 * @param   StatsJsonView  $view   JSON view for displaying the statistics.
39
	 * @param   Cache          $cache  The cache handler.
40
	 *
41
	 * @since   1.0
42
	 */
43 1
	public function __construct(StatsJsonView $view, Cache $cache)
44
	{
45 1
		$this->cache = $cache;
46 1
		$this->view  = $view;
47 1
	}
48
49
	/**
50
	 * Execute the controller.
51
	 *
52
	 * @return  boolean
53
	 *
54
	 * @since   1.0
55
	 */
56 2
	public function execute()
57
	{
58
		// Check if we are allowed to receive the raw data
59 2
		$authorizedRaw = $this->getInput()->server->getString('HTTP_JOOMLA_RAW', 'fail') === $this->getApplication()->get('stats.rawdata', false);
60
61
		// Check if a single data source is requested
62 2
		$source = $this->getInput()->getString('source');
63
64 2
		$this->view->isAuthorizedRaw($authorizedRaw);
65 2
		$this->view->setSource($source);
66
67
		// Serve cached data if the cache layer is enabled and the raw data source is not requested
68 2
		if ($this->getApplication()->get('cache.enabled', false) && !$authorizedRaw)
69 2
		{
70 1
			$key = md5(get_class($this->view) . __METHOD__ . $source);
71
72 1
			if ($this->cache->contains($key))
73 1
			{
74 1
				$body = $this->cache->fetch($key);
75 1
			}
76
			else
77
			{
78 1
				$body = $this->view->render();
79
80 1
				$this->cache->save($key, $body, $this->getApplication()->get('cache.lifetime', 900));
81
			}
82 1
		}
83
		else
84
		{
85 1
			$body = $this->view->render();
86
		}
87
88 2
		$this->getApplication()->setBody($body);
89
90 2
		return true;
91
	}
92
}
93