Completed
Push — master ( 4a9074...3e0a60 )
by Michael
03:55 queued 01:44
created

StatsJsonView::sanitizeData()   D

Complexity

Conditions 15
Paths 33

Size

Total Lines 84
Code Lines 39

Duplication

Lines 8
Ratio 9.52 %

Code Coverage

Tests 48
CRAP Score 15.0019

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 8
loc 84
ccs 48
cts 49
cp 0.9796
rs 4.9121
cc 15
eloc 39
nc 33
nop 1
crap 15.0019

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Stats\Views\Stats;
4
5
use Joomla\View\BaseJsonView;
6
7
/**
8
 * JSON response for requesting the stats data.
9
 *
10
 * @property-read  \Stats\Models\StatsModel  $model  The model object.
11
 *
12
 * @since          1.0
13
 */
14
class StatsJsonView extends BaseJsonView
15
{
16
	/**
17
	 * Flag if the response should return the raw data.
18
	 *
19
	 * @var    boolean
20
	 * @since  1.0
21
	 */
22
	private $authorizedRaw = false;
23
24
	/**
25
	 * Array holding the valid data sources.
26
	 *
27
	 * @var    array
28
	 * @since  1.0
29
	 */
30
	private $dataSources = ['php_version', 'db_type', 'db_version', 'cms_version', 'server_os'];
31
32
	/**
33
	 * The data source to return.
34
	 *
35
	 * @var    string
36
	 * @since  1.0
37
	 */
38
	private $source;
39
40
	/**
41
	 * Count of the number of items.
42
	 *
43
	 * @var    integer
44
	 * @since  1.0
45
	 */
46
	private $totalItems = 0;
47
48
	/**
49
	 * Set whether the raw data should be returned.
50
	 *
51
	 * @param   boolean  $authorizedRaw  Flag if the response should return the raw data.
52
	 *
53
	 * @return  void
54
	 *
55
	 * @since   1.0
56
	 */
57 1
	public function isAuthorizedRaw($authorizedRaw)
58
	{
59 1
		$this->authorizedRaw = $authorizedRaw;
60 1
	}
61
62
	/**
63
	 * Method to render the view.
64
	 *
65
	 * @return  string  The rendered view.
66
	 *
67
	 * @since   1.0
68
	 * @throws  \InvalidArgumentException
69
	 */
70 4
	public function render()
71
	{
72 4
		$items = $this->model->getItems($this->source);
73
74 4
		$php_version = [];
75 4
		$db_type     = [];
76 4
		$db_version  = [];
77 4
		$cms_version = [];
78 4
		$server_os   = [];
79
80 4
		if ($this->source)
81 4
		{
82 2
			return $this->processSingleSource($items);
83
		}
84
85
		// If we have the entire database, we have to loop within each group to put it all together
86 2
		foreach ($items as $group)
87
		{
88 2
			$this->totalItems += count($group);
89
90 2
			foreach ($group as $item)
0 ignored issues
show
Bug introduced by
The expression $group of type object<stdClass> is not traversable.
Loading history...
91
			{
92 2
				foreach ($this->dataSources as $source)
93
				{
94 2
					if (isset($item->$source) && !is_null($item->$source))
95 2
					{
96
						// Special case, if the server is empty then change the key to "unknown"
97 2
						if ($source === 'server_os' && empty($item->$source))
98 2
						{
99 2
							if (!isset(${$source}['unknown']))
100 2
							{
101 2
								${$source}['unknown'] = 0;
102 2
							}
103
104 2
							${$source}['unknown']++;
105 2
						}
106 View Code Duplication
						else
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...
107
						{
108 2
							if (!isset(${$source}[$item->$source]))
109 2
							{
110 2
								${$source}[$item->$source] = 0;
111 2
							}
112
113 2
							${$source}[$item->$source]++;
114
						}
115 2
					}
116 2
				}
117 2
			}
118 2
		}
119
120 2
		unset($items);
121
122
		$data = [
123 2
			'php_version' => $php_version,
124 2
			'db_type'     => $db_type,
125 2
			'db_version'  => $db_version,
126 2
			'cms_version' => $cms_version,
127 2
			'server_os'   => $server_os,
128 2
		];
129
130 2
		$responseData = $this->buildResponseData($data);
131
132 2
		$responseData['total'] = $this->totalItems;
133
134 2
		$this->addData('data', $responseData);
135
136 2
		return parent::render();
137
	}
138
139
	/**
140
	 * Set the data source.
141
	 *
142
	 * @param   string  $source  Data source to return.
143
	 *
144
	 * @return  void
145
	 *
146
	 * @since   1.0
147
	 */
148 1
	public function setSource($source)
149
	{
150 1
		$this->source = $source;
151 1
	}
152
153
	/**
154
	 * Process the raw data into the response data format.
155
	 *
156
	 * @param   array  $data  The raw data array.
157
	 *
158
	 * @return  array
159
	 *
160
	 * @since   1.0
161
	 */
162 4
	private function buildResponseData(array $data)
163
	{
164 4
		$responseData = [];
165
166 4
		foreach ($data as $key => $value)
167
		{
168 4
			foreach ($value as $name => $count)
169
			{
170
				if ($name)
171 4
				{
172 4
					$responseData[$key][] = [
173 4
						'name'  => $name,
174
						'count' => $count
175 4
					];
176 4
				}
177 4
			}
178 4
		}
179
180 4
		if (!$this->authorizedRaw)
181 4
		{
182 3
			$responseData = $this->sanitizeData($responseData);
183 3
		}
184
185 4
		return $responseData;
186
	}
187
188
	/**
189
	 * Process the response for a single data source.
190
	 *
191
	 * @param   array  $items  The source items to process.
192
	 *
193
	 * @return  string  The rendered view.
194
	 *
195
	 * @since   1.0
196
	 */
197 2
	private function processSingleSource(array $items)
198
	{
199
		$data = [
200 2
			${$this->source} = [],
201 2
		];
202
203 2
		$this->totalItems = count($items);
204
205 2
		foreach ($items as $item)
206
		{
207 2
			foreach ($this->dataSources as $source)
208
			{
209 2
				if (isset($item->$source) && !is_null($item->$source))
210 2
				{
211
					// Special case, if the server is empty then change the key to "unknown"
212 2
					if ($source === 'server_os' && empty($item->$source))
213 2
					{
214 1
						if (!isset($data[$source]['unknown']))
215 1
						{
216 1
							$data[$source]['unknown'] = 0;
217 1
						}
218
219 1
						$data[$source]['unknown']++;
220 1
					}
221 View Code Duplication
					else
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...
222
					{
223 2
						if (!isset($data[$source][$item->$source]))
224 2
						{
225 2
							$data[$source][$item->$source] = 0;
226 2
						}
227
228 2
						$data[$source][$item->$source]++;
229
					}
230 2
				}
231 2
			}
232 2
		}
233
234 2
		$responseData = $this->buildResponseData($data);
235
236 2
		$responseData['total'] = $this->totalItems;
237
238 2
		$this->addData('data', $responseData);
239
240 2
		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...
241
	}
242
243
	/**
244
	 * Sanitize the response data into summarized groups.
245
	 *
246
	 * @param   array  $responseData  The response data to sanitize.
247
	 *
248
	 * @return  array
249
	 *
250
	 * @since   1.0
251
	 */
252 3
	private function sanitizeData(array $responseData)
253
	{
254 3
		foreach ($responseData as $key => $dataGroup)
255
		{
256
			switch ($key)
257
			{
258 3
				case 'php_version':
259 3
				case 'db_version':
260
					// We're going to group by minor version branch here and convert to a percentage
261 2
					$counts = [];
262
263 2
					foreach ($dataGroup as $row)
264
					{
265 2
						$exploded = explode('.', $row['name']);
266 2
						$version  = $exploded[0] . '.' . (isset($exploded[1]) ? $exploded[1] : '0');
267
268
						// If the container does not exist, add it
269 2
						if (!isset($counts[$version]))
270 2
						{
271 2
							$counts[$version] = 0;
272 2
						}
273
274 2
						$counts[$version] += $row['count'];
275 2
					}
276
277 2
					$sanitizedData = [];
278
279 2 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...
280
					{
281 2
						$sanitizedData[$version] = round(($count / $this->totalItems) * 100, 2);
282 2
					}
283
284 2
					$responseData[$key] = $sanitizedData;
285
286 2
					break;
287
288 2
				case 'server_os':
289
					// We're going to group by operating system here
290 2
					$counts = [];
291
292 2
					foreach ($dataGroup as $row)
293
					{
294 2
						$fullOs = explode(' ', $row['name']);
295 2
						$os     = $fullOs[0];
296
297
						// If the container does not exist, add it
298 2
						if (!isset($counts[$os]))
299 2
						{
300 2
							$counts[$os] = 0;
301 2
						}
302
303 2
						$counts[$os] += $row['count'];
304 2
					}
305
306 2
					$sanitizedData = [];
307
308 2 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...
309
					{
310 2
						$sanitizedData[$os] = round(($count / $this->totalItems) * 100, 2);
311 2
					}
312
313 2
					$responseData[$key] = $sanitizedData;
314
315 2
					break;
316
317 1
				case 'db_type':
318 1
				case 'cms_version':
319 1
				default:
320
					// For now, group by the object name and figure out the percentages
321 1
					$sanitizedData = [];
322
323 1
					foreach ($dataGroup as $row)
324
					{
325 1
						$sanitizedData[$row['name']] = round(($row['count'] / $this->totalItems) * 100, 2);
326 1
					}
327
328 1
					$responseData[$key] = $sanitizedData;
329
330 1
					break;
331
			}
332 3
		}
333
334 3
		return $responseData;
335
	}
336
}
337