Completed
Push — master ( fdf5fc...3f8872 )
by Jacob
02:18
created

PhpQuickProfiler::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 2 Features 2
Metric Value
c 5
b 2
f 2
dl 0
loc 9
rs 9.6667
cc 2
eloc 5
nc 2
nop 2
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
     * Get data about files loaded for the application to current point
40
     *
41
     * @returns array
42
     */
43
    public function gatherFileData()
44
    {
45
        $files = get_included_files();
46
        $data = array();
47
        foreach ($files as $file) {
48
            array_push($data, array(
49
                'name' => $file,
50
                'size' => filesize($file)
51
            ));
52
        }
53
        return $data;
54
    }
55
56
    /**
57
     * Get data about memory usage of the application
58
     *
59
     * @returns array
60
     */
61
    public function gatherMemoryData()
62
    {
63
        $usedMemory = memory_get_peak_usage();
64
        $allowedMemory = ini_get('memory_limit');
65
        return array(
66
            'used'    => $usedMemory,
67
            'allowed' => $allowedMemory
68
        );
69
    }
70
  
71
  /*--------------------------------------------------------
72
       QUERY DATA -- DATABASE OBJECT WITH LOGGING REQUIRED
73
  ----------------------------------------------------------*/
74
  
75
  public function gatherQueryData() {
76
    $queryTotals = array();
77
    $queryTotals['count'] = 0;
78
    $queryTotals['time'] = 0;
79
    $queries = array();
80
    
81
    if($this->db != '') {
82
      $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...
83
      foreach($this->db->queries as $query) {
84
        $query = $this->attemptToExplainQuery($query);
85
        $queryTotals['time'] += $query['time'];
86
        $query['time'] = Display::getReadableTime($query['time']);
87
        $queries[] = $query;
88
      }
89
    }
90
    
91
    $queryTotals['time'] = Display::getReadableTime($queryTotals['time']);
92
    $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...
93
    $this->output['queryTotals'] = $queryTotals;
94
  }
95
  
96
  /*--------------------------------------------------------
97
       CALL SQL EXPLAIN ON THE QUERY TO FIND MORE INFO
98
  ----------------------------------------------------------*/
99
  
100
  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...
101
    try {
102
      $sql = 'EXPLAIN '.$query['sql'];
103
      $rs = $this->db->query($sql);
104
    }
105
    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...
106
    if($rs) {
107
      $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...
108
      $query['explain'] = $row;
109
    }
110
    return $query;
111
  }
112
113
    /**
114
     * Get data about speed of the application
115
     *
116
     * @returns array
117
     */
118
    public function gatherSpeedData()
119
    {
120
        $elapsedTime = microtime(true) - $this->startTime;
121
        $allowedTime = ini_get('max_execution_time');
122
        return array(
123
            'elapsed' => $elapsedTime,
124
            'allowed' => $allowedTime
125
        );
126
    }
127
128
    /**
129
     * Triggers end display of the profiling data
130
     *
131
     * @param Display $display
132
     */
133
    public function display(Display $display)
134
    {
135
        $display->setConsole($this->console);
136
        $display->setFileData($this->gatherFileData());
137
        $display->setMemoryData($this->gatherMemoryData());
138
        $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...
139
        $display->setSpeedData($this->gatherSpeedData());
140
141
        $display();
142
    }
143
}
144