Completed
Pull Request — master (#43)
by Michael
09:54
created

StatsJsonView::setSource()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * Joomla! Statistics Server
4
 *
5
 * @copyright  Copyright (C) 2013 - 2017 Open Source Matters, Inc. All rights reserved.
6
 * @license    http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License Version 2 or Later
7
 */
8
9
namespace Joomla\StatsServer\Views\Stats;
10
11
use Joomla\StatsServer\Repositories\StatisticsRepository;
12
use Joomla\View\JsonView;
13
14
/**
15
 * JSON response for requesting the stats data.
16
 */
17
class StatsJsonView extends JsonView
18
{
19
	/**
20
	 * Flag if the response should return the raw data.
21
	 *
22
	 * @var  boolean
23
	 */
24
	private $authorizedRaw = false;
25
26
	/**
27
	 * Array holding the valid data sources.
28
	 *
29
	 * @var  array
30
	 */
31
	private $dataSources = ['php_version', 'db_type', 'db_version', 'cms_version', 'server_os', 'cms_php_version', 'db_type_version'];
32
33
	/**
34
	 * Flag if the response should return the recently updated data.
35
	 *
36
	 * @var  boolean
37
	 */
38
	private $recent = false;
39
40
	/**
41
	 * Statistics repository.
42
	 *
43
	 * @var  StatisticsRepository
44
	 */
45
	private $repository;
46
47
	/**
48
	 * The data source to return.
49
	 *
50
	 * @var  string
51
	 */
52
	private $source = '';
53
54
	/**
55
	 * Count of the number of items.
56
	 *
57
	 * @var  integer
58
	 */
59
	private $totalItems = 0;
60
61
	/**
62
	 * Instantiate the view.
63
	 *
64
	 * @param   StatisticsRepository  $repository  Statistics repository.
65
	 */
66 8
	public function __construct(StatisticsRepository $repository)
67
	{
68 8
		$this->repository = $repository;
69 8
	}
70
71
	/**
72
	 * Set whether the raw data should be returned.
73
	 *
74
	 * @param   bool  $authorizedRaw  Flag if the response should return the raw data.
75
	 *
76
	 * @return  void
77
	 */
78 4
	public function isAuthorizedRaw(bool $authorizedRaw): void
79
	{
80 4
		$this->authorizedRaw = $authorizedRaw;
81 4
	}
82
83
	/**
84
	 * Set whether the recently updated data should be returned.
85
	 *
86
	 * @param   bool  $recent  Flag if the response should return the recently updated data.
87
	 *
88
	 * @return  void
89
	 */
90 1
	public function isRecent(bool $recent): void
91
	{
92 1
		$this->recent = $recent;
93 1
	}
94
95
	/**
96
	 * Method to render the view.
97
	 *
98
	 * @return  string  The rendered view.
99
	 */
100 8
	public function render()
101
	{
102 8
		if ($this->recent)
103
		{
104 1
			$items = $this->repository->getRecentlyUpdatedItems();
105
		}
106
		else
107
		{
108 7
			$items = $this->repository->getItems($this->source);
109
		}
110
111 8
		if ($this->source)
112
		{
113 3
			return $this->processSingleSource($items);
114
		}
115
116 5
		$php_version     = [];
117 5
		$db_type         = [];
118 5
		$db_version      = [];
119 5
		$cms_version     = [];
120 5
		$server_os       = [];
121
		$cms_php_version = [];
122
		$db_type_version = [];
123 5
124
		// If we have the entire database, we have to loop within each group to put it all together
125 5
		foreach ($items as $group)
126
		{
127 5
			$this->totalItems = 0;
128
129 5
			foreach ($group as $item)
130
			{
131 5
				foreach ($this->dataSources as $source)
132
				{
133
					switch ($source)
134 5
					{
135
						case 'server_os':
136 3
							if (isset($item[$source]) && $item[$source] !== null)
137
							{
138
								// Special case, if the server is empty then change the key to "unknown"
139 5
								if (empty($item[$source]))
140
								{
141 5
									$item[$source] = 'unknown';
142
								}
143
								${$source}[$item[$source]] = $item['count'];
144
							}
145
							break;
146
147 View Code Duplication
						case 'cms_php_version':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148 5
							if ((isset($item['cms_version']) && $item['cms_version'] !== null) && (isset($item['php_version']) && $item['php_version'] !== null))
149 5
							{
150 5
								$index = $item['cms_version'] . ' - ' . $item['php_version'];
151 5
								$cms_php_version[$index] = $item['count'];
152 5
								$this->totalItems += $item['count'];								
153
							}
154
							break;
155 5
156 View Code Duplication
						case 'db_type_version':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
157 5
							if ((isset($item['db_type']) && $item['db_type'] !== null) && (isset($item['db_version']) && $item['db_version'] !== null))
158
							{
159 5
								$index = $item['db_type'] . ' - ' . $item['db_version'];
160
								$db_type_version[$index] = $item['count'];
161 5
								$this->totalItems += $item['count'];								
162
							}
163
							break;
164
165
						default:
166
							if (isset($item[$source]) && $item[$source] !== null)
167
							{
168
								${$source}[$item[$source]] = $item['count'];
169
							}
170
							break;
171 5
					}
172
				}
173 5
			}
174 5
		}
175
176
		$data = [
177
			'php_version'     => $php_version,
178
			'db_type'         => $db_type,
179
			'db_version'      => $db_version,
180
			'cms_version'     => $cms_version,
181
			'server_os'       => $server_os,
182
			'cms_php_version' => $cms_php_version,
183 8
			'db_type_version' => $db_type_version,
184
		];
185 8
186
		$responseData = $this->buildResponseData($data);
187 8
188
		$responseData['total'] = $this->totalItems;
189 8
190
		$this->addData('data', $responseData);
191 8
192
		return parent::render();
193 8
	}
194 8
195 8
	/**
196
	 * Set the data source.
197
	 *
198
	 * @param   string  $source  Data source to return.
199
	 *
200
	 * @return  void
201 8
	 */
202
	public function setSource(string $source): void
203 8
	{
204
		$this->source = $source;
205 6
	}
206
207
	/**
208 8
	 * Process the raw data into the response data format.
209
	 *
210
	 * @param   array  $data  The raw data array.
211
	 *
212
	 * @return  array
213
	 */
214
	private function buildResponseData(array $data): array
215
	{
216
		$responseData = [];
217
218 3
		foreach ($data as $key => $value)
219
		{
220
			foreach ($value as $name => $count)
221 3
			{
222
				if ($name)
223
				{
224 3
					$responseData[$key][] = [
225
						'name'  => $name,
226 3
						'count' => $count,
227
					];
228
				}
229 3
			}
230
		}
231 1
232
		unset($data);
233
234 3
		if (!$this->authorizedRaw)
235 3
		{
236
			$responseData = $this->sanitizeData($responseData);
237
		}
238 3
239
		return $responseData;
240 3
	}
241
242 3
	/**
243
	 * Process the response for a single data source.
244 3
	 *
245
	 * @param   array  $items  The source items to process.
246 3
	 *
247
	 * @return  string  The rendered view.
248
	 */
249
	private function processSingleSource(array $items): string
250
	{
251
		$data = [
252
			${$this->source} = [],
253
		];
254
255
		$this->totalItems = 0;
256 6
257
		foreach ($items as $item)
258 6
		{
259
			switch ($this->source)
260 6
			{
261
				case 'server_os':
262 6
					// Special case, if the server is empty then change the key to "unknown"
263 4
					if (empty(trim($item[$this->source])))
264 4
					{
265
						$item[$this->source] = 'unknown';
266 5
					}
267
					$data[$this->source][$item[$this->source]] = $item['count'];
268 5
					break;
269
270 5
				case 'cms_php_version':
271 5
					$index = $item['cms_version'] . ' - ' . $item['php_version'];
272
					$data[$this->source][$index] = $item['count'];
273
					break;
274 5
275
				case 'db_type_version':
276 5
					$index = $item['db_type'] . ' - ' . $item['db_version'];
277
					$data[$this->source][$index] = $item['count'];
278
					break;
279 5
280
				default:
281
					$data[$this->source][$item[$this->source]] = $item['count'];
282 5
					break;
283
			}
284 5
285
			$this->totalItems += $item['count'];
286 5
		}
287
288
		$responseData = $this->buildResponseData($data);
289 5
290
		$responseData['total'] = $this->totalItems;
291 5
292
		$this->addData('data', $responseData);
293 4
294
		return parent::render();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (render() instead of processSingleSource()). Are you sure this is correct? If so, you might want to change this to $this->render().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
295 4
	}
296
297 4
	/**
298
	 * Sanitize the response data into summarized groups.
299 4
	 *
300 4
	 * @param   array  $responseData  The response data to sanitize.
301
	 *
302
	 * @return  array
303 4
	 */
304
	private function sanitizeData(array $responseData): array
305 4
	{
306
		foreach ($responseData as $key => $dataGroup)
307
		{
308 4
			switch ($key)
309
			{
310
				case 'php_version':
311 4
				case 'db_version':
312
				case 'cms_version':
313 4
					// We're going to group by minor version branch here and convert to a percentage
314
					$counts = [];
315 4
316
					foreach ($dataGroup as $row)
317
					{
318 4
						$exploded = explode('.', $row['name']);
319
						$version  = $exploded[0] . '.' . ($exploded[1] ?? '0');
320 4
321
						// If the container does not exist, add it
322 3
						if (!isset($counts[$version]))
323
						{
324
							$counts[$version] = 0;
325 3
						}
326
327 3
						$counts[$version] += $row['count'];
328
					}
329 3
330
					$sanitizedData = [];
331
332 3 View Code Duplication
					foreach ($counts as $version => $count)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
333
					{
334 3
						$sanitizedData[$version] = round(($count / $this->totalItems) * 100, 2);
335
					}
336
337
					$responseData[$key] = $sanitizedData;
338 6
339
					break;
340
341
				case 'server_os':
342
					// We're going to group by operating system here
343
					$counts = [];
344
345
					foreach ($dataGroup as $row)
346
					{
347
						$fullOs = explode(' ', $row['name']);
348
						$os     = $fullOs[0];
349
350
						// If the container does not exist, add it
351
						if (!isset($counts[$os]))
352
						{
353
							$counts[$os] = 0;
354
						}
355
356
						$counts[$os] += $row['count'];
357
					}
358
359
					$sanitizedData = [];
360
361 View Code Duplication
					foreach ($counts as $os => $count)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
362
					{
363
						$sanitizedData[$os] = round(($count / $this->totalItems) * 100, 2);
364
					}
365
366
					$responseData[$key] = $sanitizedData;
367
368
					break;
369
370
				case 'db_type':
371
				case 'cms_php_version':
372
				case 'db_type_version':
373
				default:
374
					// For now, group by the object name and figure out the percentages
375
					$sanitizedData = [];
376
377
					foreach ($dataGroup as $row)
378
					{
379
						$sanitizedData[$row['name']] = round(($row['count'] / $this->totalItems) * 100, 2);
380
					}
381
382
					$responseData[$key] = $sanitizedData;
383
384
					break;
385
			}
386
		}
387
388
		return $responseData;
389
	}
390
}
391