Completed
Pull Request — master (#39)
by Robbie
01:28
created

DebugBarDatabaseCollector::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
use DebugBar\DataCollector\AssetProvider;
4
use DebugBar\DataCollector\DataCollector;
5
use DebugBar\DataCollector\Renderable;
6
use DebugBar\DataCollector\TimeDataCollector;
7
8
/**
9
 * Collects data about SQL statements executed through the DatabaseProxy
10
 */
11
class DebugBarDatabaseCollector extends DataCollector implements Renderable, AssetProvider
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
12
{
13
    /**
14
     * @var TimeDataCollector
15
     */
16
    protected $timeCollector;
17
18
    /**
19
     * @var SS_Database
20
     */
21
    protected $db;
22
23
    /**
24
     * @return array
25
     */
26
    public function collect()
27
    {
28
        // Gather the database connector at the last minute in case it has been replaced by other modules
29
        $this->db = DB::get_conn();
30
        $this->timeCollector = DebugBar::getDebugBar()->getCollector('time');
31
32
        $data = $this->collectData($this->timeCollector);
33
34
        // Check for excessive number of queries
35
        $dbQueryWarningLevel = DebugBar::config()->warn_query_limit;
36
        if ($dbQueryWarningLevel && $data['nb_statements'] > $dbQueryWarningLevel) {
37
            DebugBar::getDebugBar()
38
                ->getCollector('messages')
39
                ->addMessage(
40
                    'Your page is running a high number of database queries. You could reduce this by implementing '
41
                    . 'caching. <a href="https://docs.silverstripe.org/en/developer_guides/performance/"'
42
                    . ' target="_blank">More information.</a>',
43
                    'warning'
44
                );
45
        }
46
47
        return $data;
48
    }
49
50
    /**
51
     * Explode comma separated elements not within parenthesis or quotes
52
     *
53
     * @param string $str
54
     * @return array
55
     */
56
    protected static function explodeFields($str)
57
    {
58
        return preg_split("/(?![^(]*\)),/", $str);
59
    }
60
61
    /**
62
     * Collects data
63
     *
64
     * @param TimeDataCollector $timeCollector
65
     * @return array
66
     */
67
    protected function collectData(TimeDataCollector $timeCollector = null)
68
    {
69
        $stmts = array();
70
71
        $total_duration = 0;
72
        $total_mem      = 0;
73
74
        $failed = 0;
75
76
        $i       = 0;
77
        $queries = $this->db->getQueries();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SS_Database as the method getQueries() does only exist in the following sub-classes of SS_Database: DebugBarDatabaseNewProxy, DebugBarDatabaseProxy. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
78
79
        $limit   = DebugBar::config()->query_limit;
80
        $warnDurationThreshold = Config::inst()->get('DebugBar', 'warn_dbqueries_threshold_seconds');
81
82
        $showDb = count(array_unique(array_map(function ($stmt) {
83
                return $stmt['database'];
84
        }, $queries))) > 1;
85
86
        foreach ($queries as $stmt) {
87
            $i++;
88
89
            $total_duration += $stmt['duration'];
90
            $total_mem += $stmt['memory'];
91
92
            if (!$stmt['success']) {
93
                $failed++;
94
            }
95
96
            if ($limit && $i > $limit) {
97
                $stmts[] = array(
98
                    'sql' => "Only the first $limit queries are shown"
99
                );
100
                break;
101
            }
102
103
            $stmts[] = array(
104
                'sql' => $stmt['short_query'],
105
                'row_count' => $stmt['rows'],
106
                'params' => $stmt['select'] ? $stmt['select'] : null,
107
                'duration' => $stmt['duration'],
108
                'duration_str' => $this->getDataFormatter()->formatDuration($stmt['duration']),
109
                'memory' => $stmt['memory'],
110
                'memory_str' => $this->getDataFormatter()->formatBytes($stmt['memory']),
111
                'is_success' => $stmt['success'],
112
                'database' => $showDb ? $stmt['database'] : null,
113
                'source' => $stmt['source'],
114
                'warn' => $stmt['duration'] > $warnDurationThreshold
115
            );
116
117
            if ($timeCollector !== null) {
118
                $timeCollector->addMeasure(
119
                    $stmt['short_query'],
120
                    $stmt['start_time'],
121
                    $stmt['end_time']
122
                );
123
            }
124
        }
125
126
        return array(
127
            'nb_statements' => count($queries),
128
            'nb_failed_statements' => $failed,
129
            'statements' => $stmts,
130
            'accumulated_duration' => $total_duration,
131
            'accumulated_duration_str' => $this->getDataFormatter()->formatDuration($total_duration),
132
            'memory_usage' => $total_mem,
133
            'memory_usage_str' => $this->getDataFormatter()->formatBytes($total_mem),
134
        );
135
    }
136
137
    /**
138
     * @return string
139
     */
140
    public function getName()
141
    {
142
        return 'db';
143
    }
144
145
    /**
146
     * @return array
147
     */
148
    public function getWidgets()
149
    {
150
        return array(
151
            "database" => array(
152
                "icon" => "inbox",
153
                "widget" => "PhpDebugBar.Widgets.SQLQueriesWidget",
154
                "map" => "db",
155
                "default" => "[]"
156
            ),
157
            "database:badge" => array(
158
                "map" => "db.nb_statements",
159
                "default" => 0
160
            )
161
        );
162
    }
163
164
    /**
165
     * @return array
166
     */
167 View Code Duplication
    public function getAssets()
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...
168
    {
169
        return array(
170
            'base_path' => '/'.DEBUGBAR_DIR.'/javascript',
171
            'base_url' => DEBUGBAR_DIR.'/javascript',
172
            'css' => 'sqlqueries/widget.css',
173
            'js' => 'sqlqueries/widget.js'
174
        );
175
    }
176
}
177