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

DatabaseCollector   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 201
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 82
c 1
b 0
f 0
dl 0
loc 201
rs 10
wmc 16

9 Methods

Rating   Name   Duplication   Size   Complexity  
A icon() 0 3 1
A getBadgeValue() 0 3 1
A isEmpty() 0 3 1
A getTitleDetails() 0 4 2
A getConnections() 0 3 1
A collect() 0 13 3
A __construct() 0 3 1
A formatTimelineData() 0 24 3
A display() 0 62 3
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
}