Completed
Push — master ( 2f6da3...fdf5fc )
by Jacob
02:08
created

PhpQuickProfiler::gatherConsoleData()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 62
Code Lines 49

Duplication

Lines 14
Ratio 22.58 %

Importance

Changes 5
Bugs 3 Features 0
Metric Value
c 5
b 3
f 0
dl 14
loc 62
rs 7.3333
cc 7
eloc 49
nc 7
nop 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A PhpQuickProfiler::gatherMemoryData() 0 9 1

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
/*****************************************
4
 * Title : PHP Quick Profiler Class
5
 * Author : Created by Ryan Campbell
6
 * URL : http://particletree.com/features/php-quick-profiler/
7
 * Description : This class processes the logs and organizes the data
8
 *  for output to the browser. Initialize this class with a start time
9
 *  at the beginning of your code, and then call the display method when
10
 *  your code is terminating.
11
*****************************************/
12
13
namespace Particletree\Pqp;
14
15
class PhpQuickProfiler
16
{
17
18
    /** @var  Particletree\Pqp\Console */
19
    protected $console;
20
21
    /** @var  integer */
22
    protected $startTime;
23
24
    /**
25
     * @param Particletree\Pqp\Console $console
26
     * @param integer                  $startTime
27
     */
28
    public function __construct(Console $console, $startTime = null)
29
    {
30
        $this->console = $console;
0 ignored issues
show
Documentation Bug introduced by
It seems like $console of type object<Particletree\Pqp\Console> is incompatible with the declared type object<Particletree\Pqp\Particletree\Pqp\Console> of property $console.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
31
32
        if (is_null($startTime)) {
33
            $startTime = microtime(true);
34
        }
35
        $this->startTime = $startTime;
0 ignored issues
show
Documentation Bug introduced by
It seems like $startTime can also be of type double. However, the property $startTime is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
36
    }
37
 
38
  /*-------------------------------------------
39
      AGGREGATE DATA ON THE FILES INCLUDED
40
  -------------------------------------------*/
41
  
42
  public function gatherFileData() {
43
    $files = get_included_files();
44
    $fileList = array();
45
    $fileTotals = array(
46
      "count" => count($files),
47
      "size" => 0,
48
      "largest" => 0,
49
    );
50
51
    foreach($files as $file) {
52
      $size = filesize($file);
53
      $fileList[] = array(
54
          'name' => $file,
55
          'size' => $this->getReadableFileSize($size)
56
        );
57
      $fileTotals['size'] += $size;
58
      if($size > $fileTotals['largest']) $fileTotals['largest'] = $size;
59
    }
60
    
61
    $fileTotals['size'] = $this->getReadableFileSize($fileTotals['size']);
62
    $fileTotals['largest'] = $this->getReadableFileSize($fileTotals['largest']);
63
64
    return array(
65
      'files' => $fileList,
66
      'fileTotals' => $fileTotals
67
    );
68
  }
69
70
    /**
71
     * Get data about memory usage of the application
72
     *
73
     * @returns array
74
     */
75
    public function gatherMemoryData()
76
    {
77
        $usedMemory = memory_get_peak_usage();
78
        $allowedMemory = ini_get('memory_limit');
79
        return array(
80
            'used'    => $usedMemory,
81
            'allowed' => $allowedMemory
82
        );
83
    }
84
  
85
  /*--------------------------------------------------------
86
       QUERY DATA -- DATABASE OBJECT WITH LOGGING REQUIRED
87
  ----------------------------------------------------------*/
88
  
89
  public function gatherQueryData() {
90
    $queryTotals = array();
91
    $queryTotals['count'] = 0;
92
    $queryTotals['time'] = 0;
93
    $queries = array();
94
    
95
    if($this->db != '') {
96
      $queryTotals['count'] += $this->db->queryCount;
0 ignored issues
show
Bug introduced by
The property db 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...
97
      foreach($this->db->queries as $query) {
98
        $query = $this->attemptToExplainQuery($query);
99
        $queryTotals['time'] += $query['time'];
100
        $query['time'] = $this->getReadableTime($query['time']);
101
        $queries[] = $query;
102
      }
103
    }
104
    
105
    $queryTotals['time'] = $this->getReadableTime($queryTotals['time']);
106
    $this->output['queries'] = $queries;
0 ignored issues
show
Bug introduced by
The property output 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...
107
    $this->output['queryTotals'] = $queryTotals;
108
  }
109
  
110
  /*--------------------------------------------------------
111
       CALL SQL EXPLAIN ON THE QUERY TO FIND MORE INFO
112
  ----------------------------------------------------------*/
113
  
114
  function attemptToExplainQuery($query) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
115
    try {
116
      $sql = 'EXPLAIN '.$query['sql'];
117
      $rs = $this->db->query($sql);
118
    }
119
    catch(Exception $e) {}
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
Bug introduced by
The class Particletree\Pqp\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
120
    if($rs) {
121
      $row = mysql_fetch_array($rs, MYSQL_ASSOC);
0 ignored issues
show
Bug introduced by
The variable $rs does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
122
      $query['explain'] = $row;
123
    }
124
    return $query;
125
  }
126
127
    /**
128
     * Get data about speed of the application
129
     *
130
     * @returns array
131
     */
132
    public function gatherSpeedData()
133
    {
134
        $elapsedTime = microtime(true) - $this->startTime;
135
        $allowedTime = ini_get('max_execution_time');
136
        return array(
137
            'elapsed' => $elapsedTime,
138
            'allowed' => $allowedTime
139
        );
140
    }
141
  
142
  /*-------------------------------------------
143
       HELPER FUNCTIONS TO FORMAT DATA
144
  -------------------------------------------*/
145
  
146
  public function getReadableFileSize($size, $retstring = null) {
147
          // adapted from code at http://aidanlister.com/repos/v/function.size_readable.php
148
         $sizes = array('bytes', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
149
150
         if ($retstring === null) { $retstring = '%01.2f %s'; }
151
152
    $lastsizestring = end($sizes);
153
154
    foreach ($sizes as $sizestring) {
155
          if ($size < 1024) { break; }
156
             if ($sizestring != $lastsizestring) { $size /= 1024; }
157
         }
158
         if ($sizestring == $sizes[0]) { $retstring = '%01d %s'; } // Bytes aren't normally fractional
0 ignored issues
show
Bug introduced by
The variable $sizestring seems to be defined by a foreach iteration on line 154. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
159
         return sprintf($retstring, $size, $sizestring);
160
  }
161
162
    /**
163
     * Static formatter for human-readable time
164
     * Only handles time up to 60 minutes gracefully
165
     *
166
     * @param integer $time time in seconds
167
     * @return string
168
     */
169 View Code Duplication
    public static function getReadableTime($time)
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...
170
    {
171
        $unit = 's';
172
173
        if ($time < 1) {
174
            $time *= 1000;
175
            $unit = 'ms';
176
        } else if ($time > 60) {
177
            $time /= 60;
178
            $unit = 'm';
179
        }
180
181
        $time = number_format($time, 3);
182
        return "{$time} {$unit}";
183
    }
184
  
185
186
    /**
187
     * Triggers end display of the profiling data
188
     *
189
     * @param Display $display
190
     */
191
    public function display(Display $display)
192
    {
193
        $display->setConsole($this->console);
194
        $display->setFileData($this->gatherFileData());
195
        $display->setMemoryData($this->gatherMemoryData());
196
        $display->setQueryData($this->gatherQueryData());
0 ignored issues
show
Documentation introduced by
$this->gatherQueryData() is of type null, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
197
        $display->setSpeedData($this->gatherSpeedData());
198
199
        $display();
200
    }
201
}
202