1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Puzzle\QueryBuilder\Queries\Snippets\Joins; |
6
|
|
|
|
7
|
|
|
use Puzzle\QueryBuilder\Snippet; |
8
|
|
|
use Puzzle\QueryBuilder\Queries\Snippets\Join; |
9
|
|
|
use Puzzle\QueryBuilder\Queries\Snippets; |
10
|
|
|
|
11
|
|
|
abstract class AbstractJoin implements Join, Snippet |
12
|
|
|
{ |
13
|
|
|
private |
14
|
|
|
$table, |
|
|
|
|
15
|
|
|
$using, |
16
|
|
|
$on; |
17
|
|
|
|
18
|
23 |
|
public function __construct(string $table, ?string $alias = null) |
19
|
|
|
{ |
20
|
23 |
|
$this->table = new Snippets\TableName($table, $alias); |
21
|
23 |
|
$this->on = []; |
22
|
23 |
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param array[string]|string $column |
|
|
|
|
26
|
|
|
*/ |
27
|
9 |
|
public function using($column): self |
28
|
|
|
{ |
29
|
9 |
|
$this->on = []; |
30
|
|
|
|
31
|
9 |
|
$this->using = new Snippets\Using($column); |
32
|
|
|
|
33
|
9 |
|
return $this; |
34
|
|
|
} |
35
|
|
|
|
36
|
16 |
|
public function on(?string $leftColumn, ?string $rightColumn): self |
37
|
|
|
{ |
38
|
16 |
|
$this->using = null; |
39
|
16 |
|
$this->on[] = new Snippets\On($leftColumn, $rightColumn); |
40
|
|
|
|
41
|
16 |
|
return $this; |
42
|
|
|
} |
43
|
|
|
|
44
|
23 |
|
public function toString(): string |
45
|
|
|
{ |
46
|
23 |
|
$joinQueryPart = sprintf( |
47
|
23 |
|
'%s %s', |
48
|
23 |
|
$this->getJoinDeclaration(), |
49
|
23 |
|
$this->table->toString() |
50
|
|
|
); |
51
|
|
|
|
52
|
23 |
|
$joinQueryPart .= $this->buildOnConditionClause(); |
53
|
23 |
|
$joinQueryPart .= $this->buildUsingConditionClause(); |
54
|
|
|
|
55
|
23 |
|
return $joinQueryPart; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
abstract protected function getJoinDeclaration(): string; |
59
|
|
|
|
60
|
23 |
|
private function buildUsingConditionClause(): string |
61
|
|
|
{ |
62
|
23 |
|
if(!$this->using instanceof Snippet) |
63
|
|
|
{ |
64
|
17 |
|
return ''; |
65
|
|
|
} |
66
|
|
|
|
67
|
9 |
|
return ' ' . $this->using->toString(); |
68
|
|
|
} |
69
|
|
|
|
70
|
23 |
|
private function buildOnConditionClause(): string |
71
|
|
|
{ |
72
|
23 |
|
$conditionClause = array(); |
73
|
|
|
|
74
|
23 |
|
foreach($this->on as $on) |
75
|
|
|
{ |
76
|
16 |
|
if($on instanceof Snippet) |
77
|
|
|
{ |
78
|
16 |
|
$conditionClause[] = $on->toString(); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
82
|
23 |
|
return empty($conditionClause) ? '' : ' ' . implode('', $conditionClause); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
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.