Total Complexity | 82 |
Total Lines | 619 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Complex classes like PDOSQLExecTask 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 PDOSQLExecTask, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
65 | class PDOSQLExecTask extends PDOTask implements Condition |
||
66 | { |
||
67 | use FileListAware; |
||
68 | use FileSetAware; |
||
69 | |||
70 | public const DELIM_ROW = 'row'; |
||
71 | public const DELIM_NORMAL = 'normal'; |
||
72 | public const DELIM_NONE = 'none'; |
||
73 | /** |
||
74 | * Count of how many statements were executed successfully. |
||
75 | * |
||
76 | * @var int |
||
77 | */ |
||
78 | private $goodSql = 0; |
||
79 | |||
80 | /** |
||
81 | * Count of total number of SQL statements. |
||
82 | * |
||
83 | * @var int |
||
84 | */ |
||
85 | private $totalSql = 0; |
||
86 | |||
87 | /** |
||
88 | * Database connection. |
||
89 | * |
||
90 | * @var PDO |
||
91 | */ |
||
92 | private $conn; |
||
93 | |||
94 | /** |
||
95 | * Formatter elements. |
||
96 | * |
||
97 | * @var PDOSQLExecFormatterElement[] |
||
98 | */ |
||
99 | private $formatters = []; |
||
100 | |||
101 | /** |
||
102 | * SQL statement. |
||
103 | * |
||
104 | * @var PDOStatement |
||
105 | */ |
||
106 | private $statement; |
||
107 | |||
108 | /** |
||
109 | * SQL input file. |
||
110 | * |
||
111 | * @var File |
||
112 | */ |
||
113 | private $srcFile; |
||
114 | |||
115 | /** |
||
116 | * SQL input command. |
||
117 | * |
||
118 | * @var string |
||
119 | */ |
||
120 | private $sqlCommand = ''; |
||
121 | |||
122 | /** |
||
123 | * SQL transactions to perform. |
||
124 | */ |
||
125 | private $transactions = []; |
||
126 | |||
127 | /** |
||
128 | * SQL Statement delimiter (for parsing files). |
||
129 | * |
||
130 | * @var string |
||
131 | */ |
||
132 | private $delimiter = ';'; |
||
133 | |||
134 | /** |
||
135 | * The delimiter type indicating whether the delimiter will |
||
136 | * only be recognized on a line by itself. |
||
137 | */ |
||
138 | private $delimiterType = self::DELIM_NONE; |
||
139 | |||
140 | /** |
||
141 | * Action to perform if an error is found. |
||
142 | */ |
||
143 | private $onError = 'abort'; |
||
144 | |||
145 | /** |
||
146 | * Encoding to use when reading SQL statements from a file. |
||
147 | */ |
||
148 | private $encoding; |
||
|
|||
149 | |||
150 | /** |
||
151 | * Fetch mode for PDO select queries. |
||
152 | * |
||
153 | * @var int |
||
154 | */ |
||
155 | private $fetchMode; |
||
156 | |||
157 | /** |
||
158 | * The name of the property to set in the event of an error |
||
159 | */ |
||
160 | private $errorProperty; |
||
161 | |||
162 | /** |
||
163 | * The name of the property that receives the number of rows |
||
164 | * returned |
||
165 | */ |
||
166 | private $statementCountProperty; |
||
167 | |||
168 | /** |
||
169 | * @var bool |
||
170 | */ |
||
171 | private $keepformat = false; |
||
172 | |||
173 | /** |
||
174 | * @var bool |
||
175 | */ |
||
176 | private $expandProperties = true; |
||
177 | |||
178 | /** |
||
179 | * Set the name of the SQL file to be run. |
||
180 | * Required unless statements are enclosed in the build file. |
||
181 | */ |
||
182 | public function setSrc(File $srcFile): void |
||
183 | { |
||
184 | $this->srcFile = $srcFile; |
||
185 | } |
||
186 | |||
187 | /** |
||
188 | * Set an inline SQL command to execute. |
||
189 | * NB: Properties are not expanded in this text. |
||
190 | * |
||
191 | * @param string $sql |
||
192 | */ |
||
193 | public function addText($sql): void |
||
196 | } |
||
197 | |||
198 | /** |
||
199 | * Creates a new PDOSQLExecFormatterElement for <formatter> element. |
||
200 | * |
||
201 | * @return PDOSQLExecFormatterElement |
||
202 | */ |
||
203 | public function createFormatter(): PDOSQLExecFormatterElement |
||
204 | { |
||
205 | $fe = new PDOSQLExecFormatterElement($this); |
||
206 | $this->formatters[] = $fe; |
||
207 | |||
208 | return $fe; |
||
209 | } |
||
210 | |||
211 | /** |
||
212 | * Add a SQL transaction to execute. |
||
213 | */ |
||
214 | public function createTransaction() |
||
215 | { |
||
216 | $t = new PDOSQLExecTransaction($this); |
||
217 | $this->transactions[] = $t; |
||
218 | |||
219 | return $t; |
||
220 | } |
||
221 | |||
222 | /** |
||
223 | * Set the statement delimiter. |
||
224 | * |
||
225 | * <p>For example, set this to "go" and delimitertype to "ROW" for |
||
226 | * Sybase ASE or MS SQL Server.</p> |
||
227 | */ |
||
228 | public function setDelimiter(string $delimiter): void |
||
229 | { |
||
230 | $this->delimiter = $delimiter; |
||
231 | } |
||
232 | |||
233 | /** |
||
234 | * Get the statement delimiter. |
||
235 | */ |
||
236 | public function getDelimiter(): string |
||
237 | { |
||
238 | return $this->delimiter; |
||
239 | } |
||
240 | |||
241 | /** |
||
242 | * Set the Delimiter type for this sql task. The delimiter type takes two |
||
243 | * values - normal and row. Normal means that any occurrence of the delimiter |
||
244 | * terminate the SQL command whereas with row, only a line containing just |
||
245 | * the delimiter is recognized as the end of the command. |
||
246 | */ |
||
247 | public function setDelimiterType(string $delimiterType): void |
||
248 | { |
||
249 | $this->delimiterType = $delimiterType; |
||
250 | } |
||
251 | |||
252 | /** |
||
253 | * Action to perform when statement fails: continue, stop, or abort |
||
254 | * optional; default "abort". |
||
255 | * |
||
256 | * @param string $action continue|stop|abort |
||
257 | */ |
||
258 | public function setOnerror($action): void |
||
259 | { |
||
260 | $this->onError = $action; |
||
261 | } |
||
262 | |||
263 | /** |
||
264 | * Sets the fetch mode to use for the PDO resultset. |
||
265 | * |
||
266 | * @param mixed $mode the PDO fetchmode int or constant name |
||
267 | * |
||
268 | * @throws BuildException |
||
269 | */ |
||
270 | public function setFetchmode($mode): void |
||
271 | { |
||
272 | if (is_numeric($mode)) { |
||
273 | $this->fetchMode = (int) $mode; |
||
274 | } else { |
||
275 | if (defined($mode)) { |
||
276 | $this->fetchMode = constant($mode); |
||
277 | } else { |
||
278 | throw new BuildException('Invalid PDO fetch mode specified: ' . $mode, $this->getLocation()); |
||
279 | } |
||
280 | } |
||
281 | } |
||
282 | |||
283 | public function getGoodSQL() |
||
284 | { |
||
285 | return $this->goodSql; |
||
286 | } |
||
287 | |||
288 | /** |
||
289 | * Property to set to "true" if a statement throws an error. |
||
290 | * |
||
291 | * @param string $errorProperty the name of the property to set in the |
||
292 | * event of an error. |
||
293 | */ |
||
294 | public function setErrorProperty(string $errorProperty): void |
||
295 | { |
||
296 | $this->errorProperty = $errorProperty; |
||
297 | } |
||
298 | |||
299 | /** |
||
300 | * Sets a given property to the number of statements processed. |
||
301 | * @param string $statementCountProperty String |
||
302 | */ |
||
303 | public function setStatementCountProperty(string $statementCountProperty): void |
||
304 | { |
||
305 | $this->statementCountProperty = $statementCountProperty; |
||
306 | } |
||
307 | |||
308 | public function setKeepformat(bool $keepformat): void |
||
309 | { |
||
310 | $this->keepformat = $keepformat; |
||
311 | } |
||
312 | |||
313 | public function setExpandProperties(bool $expandProps): void |
||
314 | { |
||
315 | $this->expandProperties = $expandProps; |
||
316 | } |
||
317 | |||
318 | /** |
||
319 | * Load the sql file and then execute it. |
||
320 | * |
||
321 | * {@inheritdoc} |
||
322 | * |
||
323 | * @throws BuildException |
||
324 | */ |
||
325 | public function main() |
||
326 | { |
||
327 | // Set a default fetchmode if none was specified |
||
328 | // (We're doing that here to prevent errors loading the class is PDO is not available.) |
||
329 | if (null === $this->fetchMode) { |
||
330 | $this->fetchMode = PDO::FETCH_ASSOC; |
||
331 | } |
||
332 | |||
333 | // Initialize the formatters here. This ensures that any parameters passed to the formatter |
||
334 | // element get passed along to the actual formatter object |
||
335 | foreach ($this->formatters as $fe) { |
||
336 | $fe->prepare($this->getLocation()); |
||
337 | } |
||
338 | |||
339 | $savedTransaction = []; |
||
340 | for ($i = 0, $size = count($this->transactions); $i < $size; ++$i) { |
||
341 | $savedTransaction[] = clone $this->transactions[$i]; |
||
342 | } |
||
343 | |||
344 | $savedSqlCommand = $this->sqlCommand; |
||
345 | |||
346 | $this->sqlCommand = trim($this->sqlCommand); |
||
347 | |||
348 | try { |
||
349 | if ( |
||
350 | null === $this->srcFile |
||
351 | && '' === $this->sqlCommand |
||
352 | && empty($this->filesets) |
||
353 | && empty($this->filelists) |
||
354 | && 0 === count($this->transactions) |
||
355 | ) { |
||
356 | throw new BuildException( |
||
357 | 'Source file or fileset/filelist, ' |
||
358 | . 'transactions or sql statement ' |
||
359 | . 'must be set!', |
||
360 | $this->getLocation() |
||
361 | ); |
||
362 | } |
||
363 | |||
364 | if (null !== $this->srcFile && !$this->srcFile->exists()) { |
||
365 | throw new BuildException('Source file does not exist!', $this->getLocation()); |
||
366 | } |
||
367 | |||
368 | // deal with the filesets |
||
369 | foreach ($this->filesets as $fs) { |
||
370 | $ds = $fs->getDirectoryScanner($this->project); |
||
371 | $srcDir = $fs->getDir($this->project); |
||
372 | $srcFiles = $ds->getIncludedFiles(); |
||
373 | // Make a transaction for each file |
||
374 | foreach ($srcFiles as $srcFile) { |
||
375 | $t = $this->createTransaction(); |
||
376 | $t->setSrc(new File($srcDir, $srcFile)); |
||
377 | } |
||
378 | } |
||
379 | |||
380 | // process filelists |
||
381 | foreach ($this->filelists as $fl) { |
||
382 | $srcDir = $fl->getDir($this->project); |
||
383 | $srcFiles = $fl->getFiles($this->project); |
||
384 | // Make a transaction for each file |
||
385 | foreach ($srcFiles as $srcFile) { |
||
386 | $t = $this->createTransaction(); |
||
387 | $t->setSrc(new File($srcDir, $srcFile)); |
||
388 | } |
||
389 | } |
||
390 | |||
391 | // Make a transaction group for the outer command |
||
392 | $t = $this->createTransaction(); |
||
393 | if ($this->srcFile) { |
||
394 | $t->setSrc($this->srcFile); |
||
395 | } |
||
396 | $t->addText($this->sqlCommand); |
||
397 | |||
398 | $this->conn = $this->getConnection(); |
||
399 | if ($this->conn === null) { |
||
400 | return; |
||
401 | } |
||
402 | |||
403 | try { |
||
404 | $this->statement = null; |
||
405 | |||
406 | // Initialize the formatters. |
||
407 | $this->initFormatters(); |
||
408 | |||
409 | try { |
||
410 | // Process all transactions |
||
411 | for ($i = 0, $size = count($this->transactions); $i < $size; ++$i) { |
||
412 | if (!$this->isAutocommit() || $this->conn->inTransaction()) { |
||
413 | $this->log('Beginning transaction', Project::MSG_VERBOSE); |
||
414 | $this->conn->beginTransaction(); |
||
415 | } |
||
416 | $this->transactions[$i]->runTransaction(); |
||
417 | if (!$this->isAutocommit() || $this->conn->inTransaction()) { |
||
418 | $this->log('Committing transaction', Project::MSG_VERBOSE); |
||
419 | $this->conn->commit(); |
||
420 | } |
||
421 | } |
||
422 | } catch (Exception $e) { |
||
423 | $this->closeConnection(); |
||
424 | |||
425 | throw new BuildException($e); |
||
426 | } |
||
427 | } catch (IOException | PDOException $e) { |
||
428 | $this->closeQuietly(); |
||
429 | $this->setErrorProp(); |
||
430 | if ('abort' === $this->onError) { |
||
431 | throw new BuildException($e->getMessage(), $this->getLocation()); |
||
432 | } |
||
433 | } |
||
434 | |||
435 | // Close the formatters. |
||
436 | $this->closeFormatters(); |
||
437 | |||
438 | $this->log( |
||
439 | $this->goodSql . ' of ' . $this->totalSql . |
||
440 | ' SQL statements executed successfully' |
||
441 | ); |
||
442 | $this->setStatementCountProp($this->goodSql); |
||
443 | } catch (Exception $e) { |
||
444 | throw new BuildException($e); |
||
445 | } finally { |
||
446 | $this->transactions = $savedTransaction; |
||
447 | $this->sqlCommand = $savedSqlCommand; |
||
448 | $this->closeConnection(); |
||
449 | } |
||
450 | } |
||
451 | |||
452 | /** |
||
453 | * read in lines and execute them. |
||
454 | * |
||
455 | * @throws BuildException |
||
456 | */ |
||
457 | public function runStatements(Reader $reader): void |
||
458 | { |
||
459 | if (self::DELIM_NONE === $this->delimiterType) { |
||
460 | $splitter = new DummyPDOQuerySplitter($this, $reader); |
||
461 | } elseif (self::DELIM_NORMAL === $this->delimiterType && 0 === strpos((string) $this->getUrl(), 'pgsql:')) { |
||
462 | $splitter = new PgsqlPDOQuerySplitter($this, $reader); |
||
463 | } else { |
||
464 | $splitter = new DefaultPDOQuerySplitter($this, $reader, $this->delimiterType); |
||
465 | } |
||
466 | |||
467 | $splitter->setExpandProperties($this->expandProperties); |
||
468 | $splitter->setKeepformat($this->keepformat); |
||
469 | |||
470 | try { |
||
471 | while (null !== ($query = $splitter->nextQuery())) { |
||
472 | $this->log('SQL: ' . $query, Project::MSG_VERBOSE); |
||
473 | $this->execSQL($query); |
||
474 | } |
||
475 | } catch (PDOException $e) { |
||
476 | throw new BuildException($e); |
||
477 | } |
||
478 | } |
||
479 | |||
480 | /** |
||
481 | * PDOSQLExecTask as condition. |
||
482 | * |
||
483 | * Returns false when the database connection fails, and true otherwise. |
||
484 | * This method only uses three properties: url (required), userId and |
||
485 | * password. |
||
486 | * |
||
487 | * The database connection is not stored in a variable, this allow to |
||
488 | * immediately close the connections since there's no reference to it. |
||
489 | * |
||
490 | * @author Jawira Portugal <[email protected]> |
||
491 | */ |
||
492 | public function evaluate(): bool |
||
493 | { |
||
494 | if (empty($this->getUrl())) { |
||
495 | throw new BuildException('url is required'); |
||
496 | } |
||
497 | |||
498 | $this->log('Trying to reach ' . $this->getUrl(), Project::MSG_DEBUG); |
||
499 | |||
500 | try { |
||
501 | new PDO($this->getUrl(), $this->getUserId(), $this->getPassword()); |
||
502 | } catch (PDOException $ex) { |
||
503 | $this->log($ex->getMessage(), Project::MSG_VERBOSE); |
||
504 | |||
505 | return false; |
||
506 | } |
||
507 | |||
508 | $this->log('Successful connection to ' . $this->getUrl(), Project::MSG_DEBUG); |
||
509 | |||
510 | return true; |
||
511 | } |
||
512 | |||
513 | /** |
||
514 | * Whether the passed-in SQL statement is a SELECT statement. |
||
515 | * This does a pretty simple match, checking to see if statement starts with |
||
516 | * 'select' (but not 'select into'). |
||
517 | * |
||
518 | * @param string $sql |
||
519 | * |
||
520 | * @return bool whether specified SQL looks like a SELECT query |
||
521 | */ |
||
522 | protected function isSelectSql($sql): bool |
||
527 | } |
||
528 | |||
529 | /** |
||
530 | * Exec the sql statement. |
||
531 | * |
||
532 | * @param string $sql |
||
533 | * |
||
534 | * @throws BuildException |
||
535 | */ |
||
536 | protected function execSQL($sql): void |
||
537 | { |
||
538 | // Check and ignore empty statements |
||
539 | if (empty(trim($sql))) { |
||
540 | return; |
||
541 | } |
||
542 | |||
543 | try { |
||
544 | ++$this->totalSql; |
||
545 | |||
546 | $this->statement = $this->conn->query($sql); |
||
547 | |||
548 | // only call processResults() for statements that return actual data (such as 'select') |
||
549 | if ($this->statement->columnCount() > 0) { |
||
550 | $this->processResults(); |
||
551 | } |
||
552 | |||
553 | $this->statement->closeCursor(); |
||
554 | $this->statement = null; |
||
555 | |||
556 | ++$this->goodSql; |
||
557 | } catch (PDOException $e) { |
||
558 | $this->log('Failed to execute: ' . $sql, Project::MSG_ERR); |
||
559 | $this->setErrorProp(); |
||
560 | if ('abort' !== $this->onError) { |
||
561 | $this->log((string) $e, Project::MSG_ERR); |
||
562 | } |
||
563 | if ('continue' !== $this->onError) { |
||
564 | throw new BuildException('Failed to execute SQL', $e); |
||
565 | } |
||
566 | $this->log($e->getMessage(), Project::MSG_ERR); |
||
567 | } |
||
568 | } |
||
569 | |||
570 | /** |
||
571 | * Returns configured PDOResultFormatter objects |
||
572 | * (which were created from PDOSQLExecFormatterElement objects). |
||
573 | * |
||
574 | * @return PDOResultFormatter[] |
||
575 | */ |
||
576 | protected function getConfiguredFormatters(): array |
||
577 | { |
||
578 | $formatters = []; |
||
579 | foreach ($this->formatters as $fe) { |
||
580 | $formatter = $fe->getFormatter(); |
||
581 | if ($formatter instanceof PlainPDOResultFormatter) { |
||
582 | $formatter->setStatementCounter($this->goodSql); |
||
583 | } |
||
584 | $formatters[] = $formatter; |
||
585 | } |
||
586 | |||
587 | return $formatters; |
||
588 | } |
||
589 | |||
590 | /** |
||
591 | * Initialize the formatters. |
||
592 | */ |
||
593 | protected function initFormatters(): void |
||
594 | { |
||
595 | $formatters = $this->getConfiguredFormatters(); |
||
596 | foreach ($formatters as $formatter) { |
||
597 | $formatter->initialize(); |
||
598 | } |
||
599 | } |
||
600 | |||
601 | /** |
||
602 | * Run cleanup and close formatters. |
||
603 | */ |
||
604 | protected function closeFormatters(): void |
||
605 | { |
||
606 | $formatters = $this->getConfiguredFormatters(); |
||
607 | foreach ($formatters as $formatter) { |
||
608 | $formatter->close(); |
||
609 | } |
||
610 | } |
||
611 | |||
612 | /** |
||
613 | * Passes results from query to any formatters. |
||
614 | * |
||
615 | * @throws PDOException |
||
616 | */ |
||
617 | protected function processResults(): void |
||
618 | { |
||
619 | $this->log('Processing new result set.', Project::MSG_VERBOSE); |
||
620 | |||
621 | $formatters = $this->getConfiguredFormatters(); |
||
622 | |||
623 | try { |
||
624 | while ($row = $this->statement->fetch($this->fetchMode)) { |
||
625 | foreach ($formatters as $formatter) { |
||
626 | $formatter->processRow($row); |
||
627 | } |
||
628 | } |
||
629 | } catch (Exception $x) { |
||
630 | $this->log('Error processing results: ' . $x->getMessage(), Project::MSG_ERR); |
||
631 | foreach ($formatters as $formatter) { |
||
632 | $formatter->close(); |
||
633 | } |
||
634 | |||
635 | throw new BuildException($x); |
||
636 | } |
||
637 | } |
||
638 | |||
639 | /** |
||
640 | * Closes current connection. |
||
641 | */ |
||
642 | protected function closeConnection(): void |
||
643 | { |
||
644 | if ($this->conn) { |
||
645 | unset($this->conn); |
||
646 | $this->conn = null; |
||
647 | } |
||
648 | } |
||
649 | |||
650 | final protected function setErrorProp(): void |
||
651 | { |
||
652 | $this->setProperty($this->errorProperty, 'true'); |
||
653 | } |
||
654 | |||
655 | final protected function setStatementCountProp(int $statementCount): void |
||
656 | { |
||
657 | $this->setProperty($this->statementCountProperty, (string) $statementCount); |
||
658 | } |
||
659 | |||
660 | /** |
||
661 | * @param string|null $name |
||
662 | * @param string $value |
||
663 | */ |
||
664 | private function setProperty(?string $name, string $value): void |
||
665 | { |
||
666 | if ($name !== null) { |
||
667 | $this->getProject()->setNewProperty($name, $value); |
||
668 | } |
||
669 | } |
||
670 | |||
671 | /** |
||
672 | * Closes an unused connection after an error and doesn't rethrow |
||
673 | * a possible PDOException |
||
674 | */ |
||
675 | private function closeQuietly(): void |
||
684 | } |
||
685 | } |
||
686 |