-
-
Notifications
You must be signed in to change notification settings - Fork 424
Expand file tree
/
Copy pathPdoStorage.php
More file actions
236 lines (204 loc) · 6.53 KB
/
Copy pathPdoStorage.php
File metadata and controls
236 lines (204 loc) · 6.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
<?php
declare(strict_types=1);
/*
* This file is part of the DebugBar package.
*
* (c) 2013 Maxime Bouroumeau-Fuseau
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace DebugBar\Storage;
use PDO;
/**
* Stores collected data into a database using PDO
*/
class PdoStorage extends AbstractStorage
{
protected PDO $pdo;
protected string $tableName;
protected array $sqlQueries = [
'save' => "INSERT INTO %tablename% (id, data, meta_utime, meta_datetime, meta_uri, meta_ip, meta_method) VALUES (?, ?, ?, ?, ?, ?, ?)",
'get' => "SELECT data FROM %tablename% WHERE id = ?",
'find' => "SELECT data FROM %tablename% %where% ORDER BY meta_datetime DESC LIMIT %limit% OFFSET %offset%",
'clear' => "DELETE FROM %tablename%",
];
public function __construct(
PDO $pdo,
string $tableName = 'phpdebugbar'
) {
$this->pdo = $pdo;
if (!preg_match('/^[A-Za-z0-9_]+$/', $tableName)) {
throw new \InvalidArgumentException('Invalid table name: ' . $tableName);
}
$this->tableName = $tableName;
}
/**
* {@inheritdoc}
*/
public function save(string $id, array $data): void
{
$stmt = $this->pdo->prepare($this->getSqlQuery('save'));
$meta = $data['__meta'];
$stmt->execute([
$id,
json_encode($data),
$meta['utime'],
$meta['datetime'] ?? null,
$meta['uri'] ?? null,
$meta['ip'] ?? null,
$meta['method'] ?? null,
]);
$this->autoPrune();
}
/**
* {@inheritdoc}
*/
public function get(string $id): array
{
$stmt = $this->pdo->prepare($this->getSqlQuery('get'));
$stmt->execute([$id]);
if (($data = $stmt->fetchColumn(0)) !== false) {
return json_decode($data, true) ?: [];
}
return [];
}
/**
* {@inheritdoc}
*/
public function find(array $filters = [], int $max = 20, int $offset = 0): array
{
$where = [];
$params = [];
$max = max(1, min(200, $max));
$offset = max(0, $offset);
foreach ($filters as $key => $value) {
if (in_array($key, ['datetime', 'uri', 'ip', 'method'], true) && strpbrk($value, '*?') === false) {
$where[] = "meta_$key = ?";
$params[] = $value;
} elseif (in_array($key, ['uri', 'ip'], true)) {
$where[] = "meta_$key LIKE ? ESCAPE '\\'";
$params[] = $this->globToSql($value, '\\');
} elseif ($key === 'utime') {
$where[] = "meta_utime > ?";
$params[] = $value;
}
}
$where = count($where) ? ' WHERE ' . implode(' AND ', $where) : '';
$stmt = $this->pdo->prepare(
$this->getSqlQuery('find', [
'where' => $where,
'offset' => (string) $offset,
'limit' => (string) $max,
])
);
$stmt->execute($params);
$results = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$data = json_decode($row['data'], true);
if ($data !== false && isset($data['__meta'])) {
$results[] = $data['__meta'];
}
unset($data);
}
return $results;
}
/**
* {@inheritdoc}
*/
public function clear(): void
{
$this->pdo->exec($this->getSqlQuery('clear'));
}
/**
* Gets the number of entries in storage
*/
public function count(): int
{
$result = $this->pdo->query("SELECT COUNT(*) FROM {$this->tableName}");
return (int) $result->fetchColumn(0);
}
public function prune(int $hours = 24): void
{
// Delete entries older than lifetime
$cutoffTime = microtime(true) - $hours * 3600;
$stmt = $this->pdo->prepare("DELETE FROM {$this->tableName} WHERE meta_utime <= ?");
$stmt->execute([$cutoffTime]);
}
/**
* Gets the PDO instance
*/
public function getPdo(): PDO
{
return $this->pdo;
}
/**
* Gets the table name
*/
public function getTableName(): string
{
return $this->tableName;
}
/**
*
* Sets the sql queries to be used
*
*/
public function setSqlQueries(array $queries): void
{
$this->sqlQueries = array_merge($this->sqlQueries, $queries);
}
public function globToSql(string $pattern, string $escapeChar = '\\'): string
{
$sqlMulti = '%';
$sqlSingle = '_';
$globMulti = '*';
$globSingle = '?';
return str_replace(
[$globMulti, $globSingle],
[$sqlMulti, $sqlSingle],
str_replace(
// If there are any SQL matching characters, escape them first
[$sqlMulti, $sqlSingle],
[$escapeChar . $sqlMulti, $escapeChar . $sqlSingle],
$pattern
)
);
}
/**
* Get a SQL Query for a task, with the variables replaced
*
*
*/
protected function getSqlQuery(string $name, array $vars = []): string
{
$sql = $this->sqlQueries[$name];
$vars = array_merge(['tablename' => $this->getTableName()], $vars);
foreach ($vars as $k => $v) {
$sql = str_replace("%$k%", $v, $sql);
}
return $sql;
}
/**
* Creates the table and indexes if they don't exist
*/
protected function createTable(): void
{
$tableName = $this->getTableName();
$this->getPdo()->exec("CREATE TABLE IF NOT EXISTS {$tableName} (
id TEXT PRIMARY KEY,
data TEXT,
meta_utime DOUBLE,
meta_datetime TEXT,
meta_uri TEXT,
meta_ip TEXT,
meta_method TEXT
)");
// Create indexes for better query performance
$this->getPdo()->exec("CREATE INDEX IF NOT EXISTS idx_{$tableName}_utime ON {$tableName} (meta_utime)");
$this->getPdo()->exec("CREATE INDEX IF NOT EXISTS idx_{$tableName}_datetime ON {$tableName} (meta_datetime)");
$this->getPdo()->exec("CREATE INDEX IF NOT EXISTS idx_{$tableName}_uri ON {$tableName} (meta_uri)");
$this->getPdo()->exec("CREATE INDEX IF NOT EXISTS idx_{$tableName}_ip ON {$tableName} (meta_ip)");
$this->getPdo()->exec("CREATE INDEX IF NOT EXISTS idx_{$tableName}_method ON {$tableName} (meta_method)");
}
}