| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace TrinityBackup\Database; |
| 6 |
|
| 7 |
if (!\defined('ABSPATH')) { |
| 8 |
exit; |
| 9 |
} |
| 10 |
|
| 11 |
final class QueryBuilder |
| 12 |
{ |
| 13 |
/** @param array<string, mixed> $row */ |
| 14 |
public function buildInsert(string $table, array $row, callable $escaper): string |
| 15 |
{ |
| 16 |
$columns = []; |
| 17 |
$values = []; |
| 18 |
|
| 19 |
foreach ($row as $column => $value) { |
| 20 |
$columns[] = $this->escapeIdentifier((string) $column); |
| 21 |
$values[] = $this->formatValue($value, $escaper); |
| 22 |
} |
| 23 |
|
| 24 |
$columnList = implode(', ', $columns); |
| 25 |
$valueList = implode(', ', $values); |
| 26 |
|
| 27 |
// Use INSERT INTO - tables are dropped and recreated before import |
| 28 |
// so there are no conflicts with existing data |
| 29 |
return sprintf( |
| 30 |
"INSERT INTO %s (%s) VALUES (%s);\n", |
| 31 |
$this->escapeIdentifier($table), |
| 32 |
$columnList, |
| 33 |
$valueList |
| 34 |
); |
| 35 |
} |
| 36 |
|
| 37 |
private function formatValue(mixed $value, callable $escaper): string |
| 38 |
{ |
| 39 |
if ($value === null) { |
| 40 |
return 'NULL'; |
| 41 |
} |
| 42 |
|
| 43 |
if (is_bool($value)) { |
| 44 |
return $value ? '1' : '0'; |
| 45 |
} |
| 46 |
|
| 47 |
if (is_int($value) || is_float($value)) { |
| 48 |
return (string) $value; |
| 49 |
} |
| 50 |
|
| 51 |
$escaped = $escaper((string) $value); |
| 52 |
return "'" . $escaped . "'"; |
| 53 |
} |
| 54 |
|
| 55 |
private function escapeIdentifier(string $identifier): string |
| 56 |
{ |
| 57 |
return '`' . str_replace('`', '``', $identifier) . '`'; |
| 58 |
} |
| 59 |
} |
| 60 |
|