|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Puzzle\QueryBuilder\Queries; |
|
6
|
|
|
|
|
7
|
|
|
use Puzzle\QueryBuilder\Query; |
|
8
|
|
|
use Puzzle\QueryBuilder\Traits\EscaperAware; |
|
9
|
|
|
use Puzzle\QueryBuilder\Queries\Snippets\Builders; |
|
10
|
|
|
|
|
11
|
|
|
class Update implements Query |
|
12
|
|
|
{ |
|
13
|
|
|
use |
|
14
|
|
|
EscaperAware, |
|
15
|
|
|
Builders\Join, |
|
16
|
|
|
Builders\Where, |
|
17
|
|
|
Builders\OrderBy, |
|
18
|
|
|
Builders\Limit; |
|
19
|
|
|
|
|
20
|
|
|
private |
|
21
|
|
|
$updatePart, |
|
|
|
|
|
|
22
|
|
|
$sets; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @param Snippets\TableName|string|null $table |
|
26
|
|
|
*/ |
|
27
|
6 |
|
public function __construct($table = null, ?string $alias = null) |
|
28
|
|
|
{ |
|
29
|
6 |
|
$this->updatePart = new Snippets\Update(); |
|
30
|
6 |
|
$this->where = new Snippets\Where(); |
|
31
|
6 |
|
$this->sets = new Snippets\Set(); |
|
32
|
6 |
|
$this->orderBy = new Snippets\OrderBy(); |
|
33
|
|
|
|
|
34
|
6 |
|
if(! empty($table)) |
|
35
|
|
|
{ |
|
36
|
3 |
|
$this->update($table, $alias); |
|
37
|
|
|
} |
|
38
|
6 |
|
} |
|
39
|
|
|
|
|
40
|
6 |
|
public function toString(): string |
|
41
|
|
|
{ |
|
42
|
|
|
$queryParts = array( |
|
43
|
6 |
|
$this->buildUpdate(), |
|
44
|
5 |
|
$this->buildJoin(), |
|
45
|
5 |
|
$this->buildSets(), |
|
46
|
5 |
|
$this->buildWhere($this->escaper), |
|
47
|
5 |
|
$this->buildOrderBy(), |
|
48
|
5 |
|
$this->buildLimit(), |
|
49
|
|
|
); |
|
50
|
|
|
|
|
51
|
5 |
|
return implode(' ', array_filter($queryParts)); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* @param Snippets\TableName|string $table |
|
56
|
|
|
*/ |
|
57
|
5 |
|
public function update($table, ?string $alias = null): self |
|
58
|
|
|
{ |
|
59
|
5 |
|
$this->updatePart->addTable($table, $alias); |
|
60
|
|
|
|
|
61
|
5 |
|
return $this; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
6 |
|
public function set(array $fields): self |
|
65
|
|
|
{ |
|
66
|
6 |
|
$this->sets->set($fields); |
|
67
|
|
|
|
|
68
|
6 |
|
return $this; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
6 |
|
private function buildUpdate(): string |
|
72
|
|
|
{ |
|
73
|
6 |
|
$updateString = $this->updatePart->toString(); |
|
74
|
|
|
|
|
75
|
6 |
|
if(empty($updateString)) |
|
76
|
|
|
{ |
|
77
|
1 |
|
throw new \RuntimeException('No table defined'); |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
5 |
|
return $updateString; |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
5 |
|
private function buildSets(): string |
|
84
|
|
|
{ |
|
85
|
5 |
|
$this->sets->setEscaper($this->escaper); |
|
86
|
|
|
|
|
87
|
5 |
|
return $this->sets->toString(); |
|
88
|
|
|
} |
|
89
|
|
|
} |
|
90
|
|
|
|
Only declaring a single property per statement allows you to later on add doc comments more easily.
It is also recommended by PSR2, so it is a common style that many people expect.