Passed
Push — main ( aa68b0...40dc38 )
by Dimitri
03:05
created

DatabaseCollector::display()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 62
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 48
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 62
rs 9.1344

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
 * This file is part of Blitz PHP framework.
5
 *
6
 * (c) 2022 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace BlitzPHP\Debug\Toolbar\Collectors;
13
14
use BlitzPHP\Database\Connection\BaseConnection;
0 ignored issues
show
Bug introduced by
The type BlitzPHP\Database\Connection\BaseConnection was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
use BlitzPHP\Event\Event;
16
17
/**
18
 * Collecteur pour l'onglet Base de données de la barre d'outils de débogage.
19
 *
20
 * @credit	<a href="https://codeigniter.com">CodeIgniter 4.2 - CodeIgniter\Debug\Toolbar\Collectors\Database</a>
21
 */
22
class DatabaseCollector extends BaseCollector
23
{
24
	/**
25
     * {@inheritDoc}
26
     */
27
    protected $hasTimeline = true;
28
29
    /**
30
     * {@inheritDoc}
31
     */
32
    protected $hasTabContent = true;
33
34
    /**
35
     * {@inheritDoc}
36
     */
37
    protected $hasVarData = false;
38
39
    /**
40
     * {@inheritDoc}
41
     */
42
    protected $title = 'Database';
43
44
    /**
45
     * Tableau de connexions à la base de données.
46
     *
47
     * @var BaseConnection[]
48
     */
49
    protected $connections;
50
51
    /**
52
     * Les instances de requête qui ont été collectées via l'événement DBQuery.
53
     *
54
     * @var stdClass[]
55
     */
56
    protected static $queries = [];
57
58
    /**
59
     * Constructeur
60
     */
61
    public function __construct()
62
    {
63
        $this->getConnections();
64
    }
65
66
67
	/**
68
     * La méthode statique utilisée lors des événements pour collecter des données.
69
     */
70
    public static function collect(Event $event)
71
    {
72
        /**
73
         * @var \BlitzPHP\Database\Result\BaseResult
74
         */
75
        $result = $event->getTarget();
76
        $config = (object) config('toolbar');
77
78
        // Fournit la valeur par défaut au cas où elle n'est pas définie
79
        $max = $config->max_queries ?: 100;
80
81
		if (count(static::$queries) < $max) {
82
            static::$queries[] = (object) $result->details();
83
		}
84
	}
85
86
	/**
87
	 * {@inheritDoc}
88
	 */
89
	protected function formatTimelineData(): array
90
	{
91
		$data = [];
92
93
		foreach ($this->connections as $alias => $connection) {
94
			$data[] = [
95
				'name'      => 'Connecting to Database: "' . $connection->getDatabase() . '". Config: "' . $alias . '"',
96
				'component' => 'Database',
97
				'start'     => $connection->getConnectStart(),
98
				'duration'  => $connection->getConnectDuration(),
99
			];
100
		}
101
102
		foreach (static::$queries as $query) {
103
			$data[] = [
104
				'name'          => 'Query',
105
				'component'     => 'Database',
106
				'query'         => $query->sql,
107
				'start'         => $query->start,
108
				'duration'      => $query->duration
109
			];
110
		}
111
112
		return $data;
113
	}
114
115
    /**
116
	 * {@inheritDoc}
117
	 */
118
	public function display(): array
119
	{
120
		// Mots clés que nous voulons mettre en gras
121
		$highlight =  [
122
			'SELECT',
123
			'DISTINCT',
124
			'FROM',
125
			'WHERE',
126
			'AND',
127
			'INNER JOIN',
128
			'LEFT JOIN',
129
			'RIGHT JOIN',
130
			'JOIN',
131
			'ORDER BY',
132
			'ASC',
133
			'DESC',
134
			'GROUP BY',
135
			'LIMIT',
136
			'INSERT',
137
			'INTO',
138
			'VALUES',
139
			'UPDATE',
140
			'OR ',
141
			'HAVING',
142
			'OFFSET',
143
			'NOT IN',
144
			'IN',
145
			'NOT LIKE',
146
			'LIKE',
147
			'COUNT',
148
			'MAX',
149
			'MIN',
150
			'ON',
151
			'AS',
152
			'AVG',
153
			'SUM',
154
			'UPPER',
155
			'LOWER',
156
			'(',
157
			')',
158
		];
159
160
		$data = [
161
			'queries' => [],
162
		];
163
164
        
165
		foreach (static::$queries as $query) {
166
			$sql = $query->sql;
167
168
			foreach ($highlight as $term) {
169
				$sql = str_replace($term, "<strong>{$term}</strong>", $sql);
170
			}
171
            
172
			$data['queries'][] = [
173
                'duration'      => (number_format($query->duration, 5) * 1000) . ' ms',
174
                'sql'           => $sql,
175
                'affected_rows' => $query->affected_rows
176
			];
177
		}
178
        
179
		return $data;
180
	}
181
182
	/**
183
	 * {@inheritDoc}
184
	 */
185
	public function getBadgeValue(): int
186
	{
187
		return count(static::$queries);
188
	}
189
190
	/**
191
	 * {@inheritDoc}
192
	 *
193
	 * @return string Le nombre de requêtes (entre parenthèses) ou une chaîne vide.
194
	 */
195
	public function getTitleDetails(): string
196
	{
197
		return '(' . count(static::$queries) . ' Queries across ' . ($countConnection = count($this->connections)) . ' Connection' .
198
				($countConnection > 1 ? 's' : '') . ')';
199
	}
200
201
	/**
202
	 * {@inheritDoc}
203
	 */
204
	public function isEmpty(): bool
205
	{
206
		return empty(static::$queries);
207
	}
208
209
	/**
210
	 * {@inheritDoc}
211
	 */
212
	public function icon(): string
213
	{
214
		return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADMSURBVEhLY6A3YExLSwsA4nIycQDIDIhRWEBqamo/UNF/SjDQjF6ocZgAKPkRiFeEhoYyQ4WIBiA9QAuWAPEHqBAmgLqgHcolGQD1V4DMgHIxwbCxYD+QBqcKINseKo6eWrBioPrtQBq/BcgY5ht0cUIYbBg2AJKkRxCNWkDQgtFUNJwtABr+F6igE8olGQD114HMgHIxAVDyAhA/AlpSA8RYUwoeXAPVex5qHCbIyMgwBCkAuQJIY00huDBUz/mUlBQDqHGjgBjAwAAACexpph6oHSQAAAAASUVORK5CYII=';
215
	}
216
217
    /**
218
     * Obtient les connexions à partir de la configuration de la base de données
219
     */
220
    private function getConnections()
221
    {
222
        $this->connections = \BlitzPHP\Config\Database::getConnections();
0 ignored issues
show
Documentation Bug introduced by
It seems like BlitzPHP\Config\Database::getConnections() of type array<string,BlitzPHP\Co...se\ConnectionInterface> is incompatible with the declared type BlitzPHP\Database\Connection\BaseConnection[] of property $connections.

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...
223
    }
224
}