|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Infrastructure\Database; |
|
6
|
|
|
|
|
7
|
|
|
use DataSource\Connection; |
|
8
|
|
|
use BasePatterns\RecordSet\Row; |
|
9
|
|
|
use BasePatterns\RecordSet\RecordSet; |
|
10
|
|
|
use DataSource\TableDataGateway\DataAdapter; |
|
11
|
|
|
|
|
12
|
|
|
class DbDataAdapter implements DataAdapter |
|
13
|
|
|
{ |
|
14
|
|
|
private string $query; |
|
15
|
|
|
|
|
16
|
|
|
private Connection $connection; |
|
17
|
|
|
|
|
18
|
3 |
|
public function __construct(string $query, Connection $connection) |
|
19
|
|
|
{ |
|
20
|
3 |
|
$this->query = $query; |
|
21
|
3 |
|
$this->connection = $connection; |
|
22
|
3 |
|
} |
|
23
|
|
|
|
|
24
|
1 |
|
public function update(RecordSet $data, string $tableName): int |
|
25
|
|
|
{ |
|
26
|
1 |
|
foreach ($data->getTable($tableName)->getRows() as $row) { |
|
27
|
1 |
|
$this->updateRow($tableName, $row); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
1 |
|
return 0; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
3 |
|
public function fill(RecordSet $data, string $tableName): int |
|
34
|
|
|
{ |
|
35
|
3 |
|
$traversable = $this->connection |
|
36
|
3 |
|
->prepare($this->query) |
|
37
|
3 |
|
->executeQuery(); |
|
38
|
|
|
|
|
39
|
3 |
|
$data->load($traversable, $tableName); |
|
40
|
|
|
|
|
41
|
3 |
|
return $data->count(); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
1 |
|
private function updateRow(string $tableName, Row $row): void |
|
45
|
|
|
{ |
|
46
|
1 |
|
if (!$row->hasChanges()) { |
|
47
|
|
|
return; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
1 |
|
list($sqlCommand, $binds) = $this->createSqlForUpdate($tableName, $row->getChanges()); |
|
51
|
|
|
|
|
52
|
1 |
|
$this->connection |
|
53
|
1 |
|
->prepare($sqlCommand) |
|
54
|
1 |
|
->execute($binds); |
|
55
|
1 |
|
} |
|
56
|
|
|
|
|
57
|
1 |
|
private function createSqlForUpdate(string $tableName, array $changes): array |
|
58
|
|
|
{ |
|
59
|
1 |
|
$sqlArray = []; |
|
60
|
1 |
|
$binds = []; |
|
61
|
1 |
|
foreach ($changes as $field => $value) { |
|
62
|
1 |
|
$sqlArray[] = sprintf("`%s`.%s = ?", $tableName, $field); |
|
63
|
1 |
|
$binds[] = $value; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return [ |
|
67
|
1 |
|
sprintf('UPDATE `%s` SET %s', $tableName, implode(', ', $sqlArray)), |
|
68
|
1 |
|
$binds |
|
69
|
|
|
]; |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|