Total Complexity | 62 |
Total Lines | 566 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Complex classes like Connection often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Connection, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
64 | class Connection |
||
65 | { |
||
66 | |||
67 | /** |
||
68 | * The PDO instance |
||
69 | * @var PDO |
||
70 | */ |
||
71 | protected PDO $pdo; |
||
72 | |||
73 | /** |
||
74 | * The PDO data source name |
||
75 | * @var string |
||
76 | */ |
||
77 | protected string $dsn = ''; |
||
78 | |||
79 | /** |
||
80 | * The list of execution query logs |
||
81 | * @var array<int, array<string, mixed>> |
||
82 | */ |
||
83 | protected array $logs = []; |
||
84 | |||
85 | /** |
||
86 | * The driver to use |
||
87 | * @var Driver |
||
88 | */ |
||
89 | protected Driver $driver; |
||
90 | |||
91 | /** |
||
92 | * The Schema instance to use |
||
93 | * @var Schema |
||
94 | */ |
||
95 | protected Schema $schema; |
||
96 | |||
97 | /** |
||
98 | * The connection configuration |
||
99 | * @var ConfigurationInterface |
||
100 | */ |
||
101 | protected ConfigurationInterface $config; |
||
102 | |||
103 | /** |
||
104 | * The connection parameters |
||
105 | * @var array<int|string, mixed> |
||
106 | */ |
||
107 | protected array $params = []; |
||
108 | |||
109 | /** |
||
110 | * @var Logger |
||
111 | */ |
||
112 | protected Logger $logger; |
||
113 | |||
114 | /** |
||
115 | * Connection constructor. |
||
116 | * @param ConfigurationInterface $config |
||
117 | * @param Logger $logger |
||
118 | * @throws ConnectionException |
||
119 | */ |
||
120 | public function __construct( |
||
135 | } |
||
136 | |||
137 | /** |
||
138 | * Connect to the database |
||
139 | * @return void |
||
140 | */ |
||
141 | public function connect(): void |
||
142 | { |
||
143 | $this->setConnectionParams(); |
||
144 | |||
145 | if ($this->config->isPersistent()) { |
||
146 | $this->persistent(true); |
||
147 | } |
||
148 | |||
149 | $attr = $this->params; |
||
150 | |||
151 | if (empty($attr)) { |
||
152 | throw new InvalidArgumentException('Invalid database options supplied'); |
||
153 | } |
||
154 | |||
155 | $driver = $attr['driver']; |
||
156 | unset($attr['driver']); |
||
157 | |||
158 | $params = []; |
||
159 | foreach ($attr as $key => $value) { |
||
160 | $params[] = is_int($key) ? $value : $key . '=' . $value; |
||
161 | } |
||
162 | |||
163 | $dsn = $driver . ':' . implode(';', $params); |
||
164 | if (in_array($driver, ['mysql', 'pgsql', 'sqlsrv'])) { |
||
165 | $charset = $this->config->getCharset(); |
||
166 | $this->config->addCommand('SET NAMES "' . $charset . '"' . ( |
||
167 | $this->config->getDriverName() === 'mysql' |
||
168 | ? ' COLLATE "' . $this->config->getCollation() . '"' |
||
169 | : '' |
||
170 | )); |
||
171 | } |
||
172 | |||
173 | $this->dsn = $dsn; |
||
174 | |||
175 | try { |
||
176 | $this->pdo = new PDO( |
||
177 | $this->dsn, |
||
178 | $this->config->getUsername(), |
||
179 | $this->config->getPassword(), |
||
180 | $this->config->getOptions() |
||
181 | ); |
||
182 | |||
183 | foreach ($this->config->getCommands() as $command) { |
||
184 | $this->pdo->exec($command); |
||
185 | } |
||
186 | } catch (PDOException $exception) { |
||
187 | $this->logger->emergency('Can not connect to database. Error message: {error}', [ |
||
188 | 'exception' => $exception, |
||
189 | 'error' => $exception->getMessage() |
||
190 | ]); |
||
191 | |||
192 | throw new ConnectionException( |
||
193 | 'Can not connect to database', |
||
194 | (int) $exception->getCode(), |
||
195 | $exception->getPrevious() |
||
196 | ); |
||
197 | } |
||
198 | } |
||
199 | |||
200 | /** |
||
201 | * |
||
202 | * @param Logger $logger |
||
203 | * @return self |
||
204 | */ |
||
205 | public function setLogger(Logger $logger): self |
||
206 | { |
||
207 | $this->logger = $logger; |
||
208 | |||
209 | return $this; |
||
210 | } |
||
211 | |||
212 | /** |
||
213 | * Return the query execution logs |
||
214 | * @return array<int, array<string, mixed>> |
||
215 | */ |
||
216 | public function getLogs(): array |
||
217 | { |
||
218 | return $this->logs; |
||
219 | } |
||
220 | |||
221 | /** |
||
222 | * Return the current connection parameters |
||
223 | * @return array<int|string, mixed> |
||
224 | */ |
||
225 | public function getParams(): array |
||
226 | { |
||
227 | return $this->params; |
||
228 | } |
||
229 | |||
230 | /** |
||
231 | * Return the current connection configuration |
||
232 | * @return ConfigurationInterface |
||
233 | */ |
||
234 | public function getConfig(): ConfigurationInterface |
||
235 | { |
||
236 | return $this->config; |
||
237 | } |
||
238 | |||
239 | /** |
||
240 | * Return the current driver instance |
||
241 | * @return Driver |
||
242 | */ |
||
243 | public function getDriver(): Driver |
||
244 | { |
||
245 | return $this->driver; |
||
246 | } |
||
247 | |||
248 | /** |
||
249 | * Return the current Schema instance |
||
250 | * @return Schema |
||
251 | */ |
||
252 | public function getSchema(): Schema |
||
255 | } |
||
256 | |||
257 | /** |
||
258 | * Set connection to be persistent |
||
259 | * @param bool $value |
||
260 | * @return self |
||
261 | */ |
||
262 | public function persistent(bool $value = true): self |
||
263 | { |
||
264 | $this->config->setOption(PDO::ATTR_PERSISTENT, $value); |
||
265 | |||
266 | return $this; |
||
267 | } |
||
268 | |||
269 | /** |
||
270 | * @return string |
||
271 | */ |
||
272 | public function getDsn(): string |
||
273 | { |
||
274 | return $this->dsn; |
||
275 | } |
||
276 | |||
277 | /** |
||
278 | * Return the instance of the PDO |
||
279 | * @return PDO |
||
280 | */ |
||
281 | public function getPDO(): PDO |
||
282 | { |
||
283 | return $this->pdo; |
||
284 | } |
||
285 | |||
286 | /** |
||
287 | * Execute the SQL query and return the result |
||
288 | * @param string $sql |
||
289 | * @param array<int, mixed> $params the query parameters |
||
290 | * @return ResultSet |
||
291 | * @throws QueryException |
||
292 | */ |
||
293 | public function query(string $sql, array $params = []): ResultSet |
||
294 | { |
||
295 | $prepared = $this->prepare($sql, $params); |
||
296 | $this->execute($prepared); |
||
297 | |||
298 | return new ResultSet($prepared['statement']); |
||
299 | } |
||
300 | |||
301 | /** |
||
302 | * Direct execute the SQL query |
||
303 | * @param string $sql |
||
304 | * @param array<int, mixed> $params the query parameters |
||
305 | * @return bool |
||
306 | * @throws QueryException |
||
307 | */ |
||
308 | public function exec(string $sql, array $params = []): bool |
||
309 | { |
||
310 | return $this->execute($this->prepare($sql, $params)); |
||
311 | } |
||
312 | |||
313 | /** |
||
314 | * Execute the SQL query and return the number |
||
315 | * of affected rows |
||
316 | * @param string $sql |
||
317 | * @param array<int, mixed> $params the query parameters |
||
318 | * @return int |
||
319 | * @throws QueryException |
||
320 | */ |
||
321 | public function count(string $sql, array $params = []): int |
||
330 | } |
||
331 | |||
332 | /** |
||
333 | * Execute the SQL query and return the first column result |
||
334 | * @param string $sql |
||
335 | * @param array<int, mixed> $params the query parameters |
||
336 | * @return mixed |
||
337 | * @throws QueryException |
||
338 | */ |
||
339 | public function column(string $sql, array $params = []) |
||
340 | { |
||
341 | $prepared = $this->prepare($sql, $params); |
||
342 | $this->execute($prepared); |
||
343 | |||
344 | $result = $prepared['statement']->fetchColumn(); |
||
345 | $prepared['statement']->closeCursor(); |
||
346 | |||
347 | return $result; |
||
348 | } |
||
349 | |||
350 | /** |
||
351 | * @param callable $callback |
||
352 | * @param mixed|null $that |
||
353 | * |
||
354 | * @return mixed |
||
355 | * |
||
356 | * @throws ConnectionException |
||
357 | */ |
||
358 | public function transaction( |
||
388 | } |
||
389 | |||
390 | /** |
||
391 | * Change the query parameters placeholder with the value |
||
392 | * @param string $query |
||
393 | * @param array<int, mixed> $params |
||
394 | * @return string |
||
395 | */ |
||
396 | protected function replaceParameters(string $query, array $params): string |
||
418 | ); |
||
419 | } |
||
420 | |||
421 | /** |
||
422 | * Prepare the query |
||
423 | * @param string $query |
||
424 | * @param array<mixed> $params |
||
425 | * @return array<string, mixed> |
||
426 | * @throws QueryException |
||
427 | */ |
||
428 | protected function prepare(string $query, array $params): array |
||
429 | { |
||
430 | try { |
||
431 | $statement = $this->pdo->prepare($query); |
||
432 | } catch (PDOException $exception) { |
||
433 | $this->logger->error('Error when prepare query [{query}]. Error message: {error}', [ |
||
434 | 'exception' => $exception, |
||
435 | 'error' => $exception->getMessage(), |
||
436 | 'query' => $query |
||
437 | ]); |
||
438 | throw new QueryPrepareException( |
||
439 | $exception->getMessage() . ' [' . $query . ']', |
||
440 | (int) $exception->getCode(), |
||
441 | $exception->getPrevious() |
||
442 | ); |
||
443 | } |
||
444 | |||
445 | return [ |
||
446 | 'statement' => $statement, |
||
447 | 'query' => $query, |
||
448 | 'params' => $params |
||
449 | ]; |
||
450 | } |
||
451 | |||
452 | /** |
||
453 | * Execute the prepared query |
||
454 | * @param array<string, mixed> $prepared |
||
455 | * @return bool the status of the execution |
||
456 | * @throws QueryException |
||
457 | */ |
||
458 | protected function execute(array $prepared): bool |
||
459 | { |
||
460 | $sql = $this->replaceParameters($prepared['query'], $prepared['params']); |
||
461 | $sqlLog = [ |
||
462 | 'query' => $prepared['query'], |
||
463 | 'parameters' => implode(', ', $prepared['params']) |
||
464 | ]; |
||
465 | |||
466 | try { |
||
467 | if ($prepared['params']) { |
||
468 | $this->bindValues($prepared['statement'], $prepared['params']); |
||
469 | } |
||
470 | $start = microtime(true); |
||
471 | $result = $prepared['statement']->execute(); |
||
472 | $sqlLog['time'] = number_format(microtime(true) - $start, 6); |
||
473 | |||
474 | $this->logs[] = $sqlLog; |
||
475 | |||
476 | $this->logger->info( |
||
477 | 'Execute Query: [{query}], parameters: [{parameters}], time: [{time}]', |
||
478 | $sqlLog |
||
479 | ); |
||
480 | } catch (PDOException $exception) { |
||
481 | $this->logger->error('Error when execute query [{sql}]. Error message: {error}', [ |
||
482 | 'exception' => $exception, |
||
483 | 'error' => $exception->getMessage(), |
||
484 | 'sql' => $sql |
||
485 | ]); |
||
486 | throw new QueryException( |
||
487 | $exception->getMessage() . ' [' . $sql . ']', |
||
488 | (int) $exception->getCode(), |
||
489 | $exception->getPrevious() |
||
490 | ); |
||
491 | } |
||
492 | |||
493 | return $result; |
||
494 | } |
||
495 | |||
496 | /** |
||
497 | * Bind the parameters values |
||
498 | * @param PDOStatement $statement |
||
499 | * @param array<int, mixed> $values |
||
500 | */ |
||
501 | protected function bindValues(PDOStatement $statement, array $values): void |
||
502 | { |
||
503 | foreach ($values as $key => $value) { |
||
504 | $param = PDO::PARAM_STR; |
||
505 | if (is_null($value)) { |
||
506 | $param = PDO::PARAM_NULL; |
||
507 | } elseif (is_int($value) || is_float($value)) { |
||
508 | $param = PDO::PARAM_INT; |
||
509 | } elseif (is_bool($value)) { |
||
510 | $param = PDO::PARAM_BOOL; |
||
511 | } |
||
512 | |||
513 | $statement->bindValue($key + 1, $value, $param); |
||
514 | } |
||
515 | } |
||
516 | |||
517 | /** |
||
518 | * Set the PDO connection parameters to use |
||
519 | * @return void |
||
520 | */ |
||
521 | protected function setConnectionParams(): void |
||
630 | } |
||
631 | } |
||
632 |