Completed
Push — master ( 47271c...bc35aa )
by Simon
02:36
created

CLog::timestampAsTable()   B

Complexity

Conditions 7
Paths 27

Size

Total Lines 62
Code Lines 37

Duplication

Lines 20
Ratio 32.26 %

Code Coverage

Tests 38
CRAP Score 7.0061

Importance

Changes 3
Bugs 2 Features 2
Metric Value
cc 7
eloc 37
c 3
b 2
f 2
nc 27
nop 0
dl 20
loc 62
ccs 38
cts 40
cp 0.95
crap 7.0061
rs 7.3333

How to fix   Long Method   

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 ultimadark\Logger;
4
5
/**
6
 * Class to log what happens.
7
 *
8
 */
9
class CLog
10
{
11
12
    /**
13
     * Properties
14
     *
15
     */
16
    private $timestamp = array();
17
    private $pos = 0;
18
    private $precision;
19
20
    /**
21
     * Constructor
22
     *
23
     * @param int $precision the precision of the rounding when presenting results.
24
     */
25 3
    public function __construct($precision = 4)
26
    {
27 3
        $this->precision = $precision;
28 3
    }
29
30
    /**
31
     * Timestamp, log a event with a time.
32
     *
33
     * @param string $domain is the module or class.
34
     * @param string $where a more specific place in the domain.
35
     * @param string $comment on the timestamp.
36
     *
37
     */
38 3
    public function timestamp($domain, $where, $comment = null)
39
    {
40 3
        $now = microtime(true);
41 3
        $this->timestamp[] = array(
42 3
          'domain'  => $domain,
43 3
          'where'   => $where,
44 3
          'comment' => $comment,
45 3
          'when'    => $now,
46 3
          'memory'  => memory_get_usage(true),
47 3
          'duration'=> 0,
48
        );
49
50 3
        if ($this->pos > 0) {
51 3
            $this->timestamp[$this->pos - 1]['memory-peak'] = memory_get_peak_usage(true);
52 3
            $this->timestamp[$this->pos - 1]['duration']    = $now - $this->timestamp[$this->pos - 1]['when'];
53 3
        }
54
    
55 3
        $this->pos++;
56 3
    }
57
58
    /**
59
     * Print all timestamp to a table.
60
     *
61
     * @return string with a html-table to display all timestamps.
62
     *
63
     */
64 2
    public function timestampAsTable()
65
    {
66
67
        // Set up the table
68 2
        $first = $this->timestamp[0]['when'];
69 2
        $last = $this->timestamp[count($this->timestamp) - 1]['when'];
70 2
        $html = "<table class='logtable'><caption>Timestamps</caption><tr><th>Domain</th><th>Where</th><th>When (sec)</th><th>Duration (sec)</th><th>Percent</th><th>Memory (MB)</th><th>Memory peak (MB)</th><th>Comment</th></tr>";
71 2
        $right = ' style="text-align: right;"';
72 2
        $total = array('domain' => array(), 'where' => array());
73
74 2
        $totalDuration = $last - $first;
75
76
        // Create the main table
77 2
        foreach ($this->timestamp as $val) {
78 2
            $when     = $val['when'] - $first;
79 2
            $duration = round($val['duration'], $this->precision);
80 2
            $percent  = round(($when) / $totalDuration * 100);
81 2
            $memory   = round($val['memory'] / 1024 / 1024, 2);
82 2
            $peak     = isset($val['memory-peak']) ? round($val['memory-peak'] / 1024 / 1024, 2): 0;
83 2
            $when     = round($when, $this->precision);
84 2
            $html .= "<tr><td>{$val['domain']}</td><td>{$val['where']}</td><td{$right}>{$when}</td><td{$right}>{$duration}</td><td{$right}>{$percent}</td><td{$right}>{$memory}</td><td{$right}>{$peak}</td><td>{$val['comment']}</td></tr>";
85 2
            @$total['domain'][$val['domain']] += $val['duration'];
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
86 2
            @$total['where'][$val['where']] += $val['duration'];
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
87 2
        }
88
89 2
        $html .= "</table><br><table class='logtable'><caption>Duration per domain</caption><tr><th>Domain</th><th>Duration</th><th>Percent</th></tr>";
90
    
91
    
92
        // Create the table grouped by domain   
93 2
        arsort($total['domain']);
94
    
95 2 View Code Duplication
        foreach ($total['domain'] as $key => $val) {
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...
96 2
            if ($totalDuration != 0) {
97 2
                $percent = round($val / $totalDuration * 100, 1);
98 2
            } else {
99
                $percent = 100;
100
            }
101
102 2
            $roundedDuration = round($val, $this->precision);
103 2
            $html .= "<tr><td>{$key}</td><td>{$roundedDuration}</td><td>{$percent}</td></tr>";
104 2
        }
105
106 2
        $html .= "</table><br><table class='logtable'><caption>Duration per area</caption><tr><th>Area</th><th>Duration</th><th>Percent</th></tr>";
107
    
108
        // Create the table grouped by area
109 2
        arsort($total['where']);
110
111 2 View Code Duplication
        foreach ($total['where'] as $key => $val) {
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...
112 2
            if ($totalDuration != 0) {
113 2
                $percent = round($val / $totalDuration * 100, 1);
114 2
            } else {
115
                $percent = 100;
116
            }  
117
118 2
            $roundedDuration = round($val, $this->precision);
119 2
            $html .= "<tr><td>{$key}</td><td>{$roundedDuration}</td><td>{$percent}</td></tr>";
120 2
        }
121
122 2
        $html .= "</table>";
123
124 2
        return $html;
125
    }
126
127
    /**
128
     * Returns load time of the page
129
     *
130
     * @return The page load time.
131
     *
132
     */
133
    public function pageLoadTime()
134
    {
135
        $first = $this->timestamp[0]['when'];
136
        $last = $this->timestamp[count($this->timestamp) - 1]['when'];
137
        $loadtime = round($last - $first, 3);
138
        return $loadtime;
139
    }
140
141
    /**
142
     * Get the memory peak.
143
     *
144
     * @return The memory peak.
145
     *
146
     */
147
    public function memoryPeak()
148
    {
149
        $peak = round(memory_get_peak_usage(true) / 1024 / 1024, 2);
150
        return $peak;
151
    }
152
153
    /**
154
     * Get the number of timestamps made so far.
155
     *
156
     * @return Number of timestamps.
157
     *
158
     */
159 1
    public function numberOfTimestamps()
160
    {
161 1
        return count($this->timestamp);
162
    }
163
164
    /**
165
     * Get the most time consuming domain.
166
     *
167
     * @return The most time consuming domain.
168
     *
169
     */
170
    public function mostTimeConsumingDomain()
171
    {
172
        $total = array();
173
174
        // Gather total duration data of each domain
175
        foreach ($this->timestamp as $val) {
176
            $duration = round($val['duration'], $this->precision);
177
            @$total[$val['domain']] += $duration;
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
178
        }
179
180
        // Get the key of the most time consuming element
181
        $mostConsumingTime = 0;
182
        $mostConsumingDomain = "";
183
        foreach ($total as $key => $val) {
184
            if ($val >= $mostConsumingTime) {
185
                $mostConsumingDomain = $key;
186
                $mostConsumingTime = $val;
187
            }
188
        }
189
190
        return $mostConsumingDomain;
191
    }
192
}
193