|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace HexMakina\Crudites\Queries; |
|
4
|
|
|
|
|
5
|
|
|
use HexMakina\Crudites\CruditesException; |
|
6
|
|
|
use HexMakina\BlackBox\Database\TableManipulationInterface; |
|
7
|
|
|
|
|
8
|
|
|
class Update extends BaseQuery |
|
9
|
|
|
{ |
|
10
|
|
|
use ClauseWhere; |
|
11
|
|
|
|
|
12
|
|
|
private $alterations = []; |
|
13
|
|
|
|
|
14
|
|
|
public function __construct(TableManipulationInterface $table, $update_data = [], $conditions = []) |
|
15
|
|
|
{ |
|
16
|
|
|
$this->table = $table; |
|
17
|
|
|
$this->connection = $table->connection(); |
|
18
|
|
|
|
|
19
|
|
|
if (!empty($update_data)) { |
|
20
|
|
|
$this->addBindings($update_data); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
if (!empty($conditions)) { |
|
24
|
|
|
if (is_array($conditions)) { |
|
25
|
|
|
$this->whereFieldsEQ($conditions); |
|
26
|
|
|
} elseif (is_string($conditions)) { |
|
27
|
|
|
$this->where($conditions); |
|
28
|
|
|
} |
|
29
|
|
|
} |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function addBindings($update_data): array |
|
33
|
|
|
{ |
|
34
|
|
|
$binding_names = []; |
|
35
|
|
|
foreach ($update_data as $field_name => $value) { |
|
36
|
|
|
$column = $this->table->column($field_name); |
|
37
|
|
|
if (is_null($column)) { |
|
38
|
|
|
continue; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
if ($value === '' && $column->isNullable()) { |
|
42
|
|
|
$value = null; |
|
43
|
|
|
} elseif (empty($value) && $column->type()->isBoolean()) { //empty '', 0, false |
|
44
|
|
|
$value = 0; |
|
45
|
|
|
} |
|
46
|
|
|
$binding_names[$field_name] = $this->addBinding($field_name, $value); |
|
47
|
|
|
$this->alterations [] = $this->backTick($field_name) . ' = ' . $binding_names[$field_name]; |
|
48
|
|
|
} |
|
49
|
|
|
return $binding_names; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
public function generate(): string |
|
53
|
|
|
{ |
|
54
|
|
|
if (empty($this->alterations)) { |
|
55
|
|
|
throw new CruditesException('UPDATE_NO_ALTERATIONS'); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
// prevents haphazrdous generation of massive update query, must use statement setter for such jobs |
|
59
|
|
|
if (empty($this->where)) { |
|
60
|
|
|
throw new CruditesException('UPDATE_NO_CONDITIONS'); |
|
61
|
|
|
} |
|
62
|
|
|
$set = implode(', ', $this->alterations); |
|
63
|
|
|
$where = $this->generateWhere(); |
|
64
|
|
|
$ret = sprintf('UPDATE `%s` SET %s %s;', $this->table->name(), $set, $where); |
|
65
|
|
|
return $ret; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|