Completed
Pull Request — master (#101)
by
unknown
59:32
created

DataModel::getConfigDataRows()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 0
cts 17
cp 0
rs 9.3554
c 0
b 0
f 0
cc 5
nc 9
nop 0
crap 30
1
<?php
2
3
namespace OpCacheGUI\OpCache;
4
5
6
class DataModel
7
{
8
    private $_configuration;
9
    private $_status;
10
    private $_d3Scripts = array();
11
12
    public function __construct()
13
    {
14
        $this->_configuration = opcache_get_configuration();
15
        $this->_status = opcache_get_status();
16
    }
17
18
    public function getPageTitle()
19
    {
20
        return 'PHP ' . phpversion() . " with OpCache {$this->_configuration['version']['version']}";
21
    }
22
23
    public function getStatusDataRows()
24
    {
25
        $rows = array();
26
        foreach ($this->_status as $key => $value) {
27
            if ($key === 'scripts') {
28
                continue;
29
            }
30
31
            if (is_array($value)) {
32
                foreach ($value as $k => $v) {
0 ignored issues
show
Bug introduced by
The expression $value of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
33
                    if ($v === false) {
34
                        $value = 'false';
35
                    }
36
                    if ($v === true) {
37
                        $value = 'true';
38
                    }
39
                    if ($k === 'used_memory' || $k === 'free_memory' || $k === 'wasted_memory') {
40
                        $v = $this->_size_for_humans(
41
                            $v
42
                        );
43
                    }
44
                    if ($k === 'current_wasted_percentage' || $k === 'opcache_hit_rate') {
45
                        $v = number_format(
46
                                $v,
47
                                2
48
                            ) . '%';
49
                    }
50
                    if ($k === 'blacklist_miss_ratio') {
51
                        $v = number_format($v, 2) . '%';
52
                    }
53
                    if ($k === 'start_time' || $k === 'last_restart_time') {
54
                        $v = ($v ? date(DATE_RFC822, $v) : 'never');
55
                    }
56
                    if (THOUSAND_SEPARATOR === true && is_int($v)) {
57
                        $v = number_format($v);
58
                    }
59
60
                    $rows[] = "<tr><th>$k</th><td>$v</td></tr>\n";
61
                }
62
                continue;
63
            }
64
            if ($value === false) {
65
                $value = 'false';
66
            }
67
            if ($value === true) {
68
                $value = 'true';
69
            }
70
            $rows[] = "<tr><th>$key</th><td>$value</td></tr>\n";
71
        }
72
73
        return implode("\n", $rows);
74
    }
75
76
    public function getConfigDataRows()
77
    {
78
        $rows = array();
79
        foreach ($this->_configuration['directives'] as $key => $value) {
80
            if ($value === false) {
81
                $value = 'false';
82
            }
83
            if ($value === true) {
84
                $value = 'true';
85
            }
86
            if ($key == 'opcache.memory_consumption') {
87
                $value = $this->_size_for_humans($value);
88
            }
89
            $rows[] = "<tr><th>$key</th><td>$value</td></tr>\n";
90
        }
91
92
        return implode("\n", $rows);
93
    }
94
95
    public function getScriptStatusRows()
96
    {
97
        foreach ($this->_status['scripts'] as $key => $data) {
98
            $dirs[dirname($key)][basename($key)] = $data;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$dirs was never initialized. Although not strictly required by PHP, it is generally a good practice to add $dirs = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
99
            $this->_arrayPset($this->_d3Scripts, $key, array(
100
                'name' => basename($key),
101
                'size' => $data['memory_consumption'],
102
            ));
103
        }
104
105
        asort($dirs);
106
107
        $basename = '';
108
        while (true) {
109
            if (count($this->_d3Scripts) != 1) break;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
110
            $basename .= DIRECTORY_SEPARATOR . key($this->_d3Scripts);
111
            $this->_d3Scripts = reset($this->_d3Scripts);
112
        }
113
114
        $this->_d3Scripts = $this->_processPartition($this->_d3Scripts, $basename);
115
        $id = 1;
116
117
        $rows = array();
118
        foreach ($dirs as $dir => $files) {
119
            $count = count($files);
120
            $file_plural = $count > 1 ? 's' : null;
121
            $m = 0;
122
            foreach ($files as $file => $data) {
123
                $m += $data["memory_consumption"];
124
            }
125
            $m = $this->_size_for_humans($m);
126
127
            if ($count > 1) {
128
                $rows[] = '<tr>';
129
                $rows[] = "<th class=\"clickable\" id=\"head-{$id}\" colspan=\"3\" onclick=\"toggleVisible('#head-{$id}', '#row-{$id}')\">{$dir} ({$count} file{$file_plural}, {$m})</th>";
130
                $rows[] = '</tr>';
131
            }
132
133
            foreach ($files as $file => $data) {
134
                $rows[] = "<tr id=\"row-{$id}\">";
135
                $rows[] = "<td>" . $this->_format_value($data["hits"]) . "</td>";
136
                $rows[] = "<td>" . $this->_size_for_humans($data["memory_consumption"]) . "</td>";
137
                $rows[] = $count > 1 ? "<td>{$file}</td>" : "<td>{$dir}/{$file}</td>";
138
                $rows[] = '</tr>';
139
            }
140
141
            ++$id;
142
        }
143
144
        return implode("\n", $rows);
145
    }
146
147
    public function getScriptStatusCount()
148
    {
149
        return count($this->_status["scripts"]);
150
    }
151
152
    public function getGraphDataSetJson()
153
    {
154
        $dataset = array();
155
        $dataset['memory'] = array(
156
            $this->_status['memory_usage']['used_memory'],
157
            $this->_status['memory_usage']['free_memory'],
158
            $this->_status['memory_usage']['wasted_memory'],
159
        );
160
161
        $dataset['keys'] = array(
162
            $this->_status['opcache_statistics']['num_cached_keys'],
163
            $this->_status['opcache_statistics']['max_cached_keys'] - $this->_status['opcache_statistics']['num_cached_keys'],
164
            0
165
        );
166
167
        $dataset['hits'] = array(
168
            $this->_status['opcache_statistics']['misses'],
169
            $this->_status['opcache_statistics']['hits'],
170
            0,
171
        );
172
173
        $dataset['restarts'] = array(
174
            $this->_status['opcache_statistics']['oom_restarts'],
175
            $this->_status['opcache_statistics']['manual_restarts'],
176
            $this->_status['opcache_statistics']['hash_restarts'],
177
        );
178
179
        if (THOUSAND_SEPARATOR === true) {
180
            $dataset['TSEP'] = 1;
181
        } else {
182
            $dataset['TSEP'] = 0;
183
        }
184
185
        return json_encode($dataset);
186
    }
187
188
    public function getHumanUsedMemory()
189
    {
190
        return $this->_size_for_humans($this->getUsedMemory());
191
    }
192
193
    public function getHumanFreeMemory()
194
    {
195
        return $this->_size_for_humans($this->getFreeMemory());
196
    }
197
198
    public function getHumanWastedMemory()
199
    {
200
        return $this->_size_for_humans($this->getWastedMemory());
201
    }
202
203
    public function getUsedMemory()
204
    {
205
        return $this->_status['memory_usage']['used_memory'];
206
    }
207
208
    public function getFreeMemory()
209
    {
210
        return $this->_status['memory_usage']['free_memory'];
211
    }
212
213
    public function getWastedMemory()
214
    {
215
        return $this->_status['memory_usage']['wasted_memory'];
216
    }
217
218
    public function getWastedMemoryPercentage()
219
    {
220
        return number_format($this->_status['memory_usage']['current_wasted_percentage'], 2);
221
    }
222
223
    public function getD3Scripts()
224
    {
225
        return $this->_d3Scripts;
226
    }
227
228
    private function _processPartition($value, $name = null)
229
    {
230
        if (array_key_exists('size', $value)) {
231
            return $value;
232
        }
233
234
        $array = array('name' => $name, 'children' => array());
235
236
        foreach ($value as $k => $v) {
237
            $array['children'][] = $this->_processPartition($v, $k);
238
        }
239
240
        return $array;
241
    }
242
243
    private function _format_value($value)
0 ignored issues
show
Coding Style introduced by
Method name "DataModel::_format_value" is not in camel caps format
Loading history...
244
    {
245
        if (THOUSAND_SEPARATOR === true) {
246
            return number_format($value);
247
        } else {
248
            return $value;
249
        }
250
    }
251
252
    private function _size_for_humans($bytes)
0 ignored issues
show
Coding Style introduced by
Method name "DataModel::_size_for_humans" is not in camel caps format
Loading history...
253
    {
254
        if ($bytes > 1048576) {
255
            return sprintf('%.2f&nbsp;MB', $bytes / 1048576);
256
        } else {
257
            if ($bytes > 1024) {
258
                return sprintf('%.2f&nbsp;kB', $bytes / 1024);
259
            } else {
260
                return sprintf('%d&nbsp;bytes', $bytes);
261
            }
262
        }
263
    }
264
265
    // Borrowed from Laravel
266
    private function _arrayPset(&$array, $key, $value)
267
    {
268
        if (is_null($key)) return $array = $value;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
269
        $keys = explode(DIRECTORY_SEPARATOR, ltrim($key, DIRECTORY_SEPARATOR));
270
        while (count($keys) > 1) {
271
            $key = array_shift($keys);
272
            if (!isset($array[$key]) || !is_array($array[$key])) {
273
                $array[$key] = array();
274
            }
275
            $array =& $array[$key];
276
        }
277
        $array[array_shift($keys)] = $value;
278
        return $array;
279
    }
280
281
}