Completed
Push — master ( c6e8cc...5bd743 )
by Jacob
02:18
created

Display::formatSpeedData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 9
rs 9.6667
cc 1
eloc 5
nc 1
nop 0
1
<?php
2
3
/*****************************************
4
 * Title : Php Quick Profiler Display Class
5
 * Author : Created by Ryan Campbell
6
 * URL : http://particletree.com/features/php-quick-profiler/
7
 * Description : This is a hacky way of pushing profiling logic to the
8
 *  PQP HTML. This is great because it will just work in your project,
9
 *  but it is hard to maintain and read.
10
*****************************************/
11
12
namespace Particletree\Pqp;
13
14
class Display
15
{
16
17
    /** @var  array */
18
    protected $defaults = array(
19
        'script_path' => 'asset/script.js',
20
        'style_path'  => 'asset/style.css'
21
    );
22
23
    /** @var  array */
24
    protected $options;
25
26
    /** @var  Console */
27
    protected $console;
28
29
    /** @var  array */
30
    protected $speedData;
31
32
    /** @var  array */
33
    protected $queryData;
34
35
    /** @var  array */
36
    protected $memoryData;
37
38
    /** @var  array */
39
    protected $fileData;
40
41
    /**
42
     * @param array $options
43
     */
44
    public function __construct(array $options = array())
45
    {
46
        $options = array_intersect_key($options, $this->defaults);
47
        $this->options = array_replace($this->defaults, $options);
48
    }
49
50
    /**
51
     * @param Console $console
52
     */
53
    public function setConsole(Console $console)
54
    {
55
        $this->console = $console;
56
    }
57
58
    /**
59
     * @return array
60
     */
61
    protected function formatConsoleData()
62
    {
63
        $console_data = array(
64
            'messages' => array(),
65
            'meta'    => array(
66
                'log'    => 0,
67
                'memory' => 0,
68
                'error'  => 0,
69
                'speed'  => 0
70
            )
71
        );
72
        foreach ($this->console->getLogs() as $log) {
73
            switch($log['type']) {
74
                case 'log':
75
                    $message = array(
76
                        'message' => print_r($log['data'], true),
77
                        'type'    => 'log'
78
                    );
79
                    $console_data['meta']['log']++;
80
                    break;
81
                case 'memory':
82
                    $message = array(
83
                        'message' => (!empty($log['data_type']) ? "{$log['data_type']}: " : '') . $log['name'],
84
                        'data'    => $this->getReadableMemory($log['data']),
85
                        'type'    => 'memory'
86
                    );
87
                    $console_data['meta']['memory']++;
88
                    break;
89
                case 'error':
90
                    $message = array(
91
                        'message' => "Line {$log['line']}: {$log['data']} in {$log['file']}",
92
                        'type'    => 'error'
93
                    );
94
                    $console_data['meta']['error']++;
95
                    break;
96
                case 'speed':
97
                    $elapsedTime = $log['data'] - $this->startTime;
0 ignored issues
show
Bug introduced by
The property startTime does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
98
                    $message = array(
99
                        'message' => $log['name'],
100
                        'data'    => $this->getReadableTime($elapsedTime),
101
                        'type'    => 'speed'
102
                    );
103
                    $console_data['meta']['speed']++;
104
                    break;
105
                default:
106
                    $message = array(
107
                        'message' => "Unrecognized console log type: {$log['type']}",
108
                        'type'    => 'error'
109
                    );
110
                    $console_data['meta']['error']++;
111
                    break;
112
            }
113
            array_push($console_data['messages'], $message);
114
        }
115
        return $console_data;
116
    }
117
118
    /**
119
     * Sets file data
120
     *
121
     * @param array $data
122
     */
123
    public function setFileData(array $data)
124
    {
125
        $this->fileData = $data;
126
    }
127
128
    /**
129
     * @return array
130
     */
131 View Code Duplication
    protected function formatFileData()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
132
    {
133
        $fileData = array(
134
            'messages' => array(),
135
            'meta'     => array(
136
                'count'   => count($this->fileData),
137
                'size'    => 0,
138
                'largest' => 0
139
            )
140
        );
141
142
        foreach ($this->fileData as $file) {
143
            array_push($fileData['messages'], array(
144
                'message' => $file['name'],
145
                'data'    => $this->getReadableMemory($file['size'])
146
            ));
147
148
            $fileData['meta']['size'] += $file['size'];
149
            if ($file['size'] > $fileData['meta']['largest']) {
150
                $fileData['meta']['largest'] = $file['size'];
151
            }
152
        }
153
154
        $fileData['meta']['size'] = $this->getReadableMemory($fileData['meta']['size']);
155
        $fileData['meta']['largest'] = $this->getReadableMemory($fileData['meta']['largest']);
156
157
        return $fileData;
158
    }
159
160
    /**
161
     * Sets memory data
162
     *
163
     * @param array $data
164
     */
165
    public function setMemoryData(array $data)
166
    {
167
        $this->memoryData = $data;
168
    }
169
170
    /**
171
     * @return array
172
     */
173
    public function formatMemoryData()
174
    {
175
        return array(
176
            'meta' => array(
177
                'used'    => $this->getReadableMemory($this->memoryData['used']),
178
                'allowed' => $this->memoryData['allowed']
179
            )
180
        );
181
    }
182
183
    /**
184
     * Sets query data
185
     *
186
     * @param array $data
187
     */
188
    public function setQueryData(array $data)
189
    {
190
        $this->queryData = $data;
191
    }
192
193
    /**
194
     * @return array
195
     */
196 View Code Duplication
    public function formatQueryData()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
197
    {
198
        $queryData = array(
199
            'messages' => array(),
200
            'meta'     => array(
201
                'count'   => count($this->queryData),
202
                'time'    => 0,
203
                'slowest' => 0
204
            )
205
        );
206
207
        foreach ($this->queryData as $query) {
208
            array_push($queryData['messages'], array(
209
                'message'  => $query['sql'],
210
                'sub_data' => array_filter($query['explain']),
211
                'data'     => $this->getReadableTime($query['time'])
212
            ));
213
            $queryData['meta']['time'] += $query['time'];
214
            if ($query['time'] > $queryData['meta']['slowest']) {
215
                $queryData['meta']['slowest'] = $query['time'];
216
            }
217
        }
218
219
        $queryData['meta']['time'] = $this->getReadableTime($queryData['meta']['time']);
220
        $queryData['meta']['slowest'] = $this->getReadableTime($queryData['meta']['slowest']);
221
222
        return $queryData;
223
    }
224
225
    /**
226
     * Sets speed data
227
     *
228
     * @param array $data
229
     */
230
    public function setSpeedData(array $data)
231
    {
232
        $this->speedData = $data;
233
    }
234
235
    /**
236
     * @return array
237
     */
238
    protected function formatSpeedData()
239
    {
240
        return array(
241
            'meta' => array(
242
              'elapsed' => $this->getReadableTime($this->speedData['elapsed']),
243
              'allowed' => $this->getReadableTime($this->speedData['allowed'], 0)
244
            )
245
        );
246
    }
247
248
    /**
249
     * Formatter for human-readable time
250
     * Only handles time up to 60 minutes gracefully
251
     *
252
     * @param double  $time
253
     * @param integer $percision
254
     * @return string
255
     */
256
    protected function getReadableTime($time, $percision = 3)
257
    {
258
        $unit = 's';
259
        if ($time < 1) {
260
            $time *= 1000;
261
            $unit = 'ms';
262
        } else if ($time > 60) {
263
            $time /= 60;
264
            $unit = 'm';
265
        }
266
        $time = number_format($time, $percision);
267
        return "{$time} {$unit}";
268
    }
269
270
    /**
271
     * Formatter for human-readable memory
272
     * Only handles time up to a few gigs gracefully
273
     *
274
     * @param double  $size
275
     * @param integer $percision
276
     */
277
    protected function getReadableMemory($size, $percision = 2)
278
    {
279
        $unitOptions = array('b', 'k', 'M', 'G');
280
281
        $base = log($size, 1024);
282
283
        $memory = round(pow(1024, $base - floor($base)), $percision);
284
        $unit = $unitOptions[floor($base)];
285
        return "{$memory} {$unit}";
286
    }
287
 
288
    public function __invoke()
289
    {
290
        $console= $this->formatConsoleData();
291
        $speed= $this->formatSpeedData();
292
        $query= $this->formatQueryData();
293
        $memory= $this->formatMemoryData();
294
        $files= $this->formatFileData();
295
296
        $header = array(
0 ignored issues
show
Unused Code introduced by
$header is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
297
          'console' => count($console['messages']),
298
          'speed'   => $speed['meta']['elapsed'],
299
          'query'   => $query['meta']['count'],
300
          'memory'  => $memory['meta']['used'],
301
          'files'   => $files['meta']['count']
302
        );
303
304
        $speed['messages'] = array_filter($console['messages'], function ($message) {
305
            return $message['type'] == 'speed';
306
        });
307
308
        $memory['messages'] = array_filter($console['messages'], function ($message) {
309
            return $message['type'] == 'memory';
310
        });
311
312
        // todo is this really the best way to load these?
313
        $styles = file_get_contents(__DIR__ . "./../{$this->options['style_path']}");
0 ignored issues
show
Unused Code introduced by
$styles is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
314
        $script = file_get_contents(__DIR__ . "./../{$this->options['script_path']}");
0 ignored issues
show
Unused Code introduced by
$script is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
315
316
        require_once __DIR__ .'/../asset/display.html';
317
    }
318
}	
319