Passed
Push — main ( 4745a3...0ccf81 )
by Sammy
08:01
created

Join::alias()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace HexMakina\Crudites\Grammar\Clause;
4
5
use HexMakina\Crudites\Grammar\Predicate;
6
7
/**
8
 * LEFT JOIN, two ways
9
 * (new Join('cbx_order', 'Orders'))->on('user_id', 'User', 'id')->type('LEFT');
10
 * (new Join('cbx_order', 'Orders'))->on('user_id', 'User', 'id')->left();
11
12
 * INNER JOIN, with helper, before on
13
 * (new Join('cbx_order', 'Orders'))->inner()->on('user_id', 'User', 'id');
14
 */
15
16
class Join extends Clause
17
{
18
    protected string $type;
19
20
    protected string $table;
21
    protected string $alias;
22
23
    protected string $on = null;
24
    
25
    public function __construct(string $table, string $alias = null)
26
    {
27
        $this->type = '';
28
        $this->table = $table;
29
        $this->alias = $alias ?? $table;
30
    }
31
32
    public function type(string $join_type): self
33
    {
34
        $this->type = $join_type;
35
36
        return $this;
37
    }
38
39
    public function on($column, $join_table, $join_column): self
40
    {
41
        $this->on = (string)(new Predicate([$this->alias, $column], '=', [$join_table, $join_column]));
42
        
43
        return $this;
44
    }
45
46
    public function alias(): string
47
    {
48
        return $this->alias;
49
    }
50
51
    public function table(): string
52
    {
53
        return $this->table;
54
    }
55
56
    public function __toString(): string
57
    {
58
        return sprintf('%s JOIN `%s` %s ON %s', $this->type, $this->table, $this->alias, $this->on);
59
    }
60
61
    public function name(): string
62
    {
63
        return self::JOIN;
64
    }
65
}