Completed
Branch develop (6af1b6)
by Henry
08:27
created

Select::limit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 6
rs 10
1
<?php
2
namespace Divergence\IO\Database\Query;
3
4
class Select extends AbstractQuery
5
{
6
    public ?string $where;
7
    public ?string $having;
8
    public ?string $limit;
9
    public string $expression = '*';
10
    public bool $calcFoundRows = false;
11
12
    public function expression(string $expression): Select
13
    {
14
        $this->expression = $expression;
15
        return $this;
16
    }
17
18
    public function where(string $where): Select
19
    {
20
        $this->where = $where;
21
        return $this;
22
    }
23
24
    public function having(string $having): Select
25
    {
26
        $this->having = $having;
27
        return $this;
28
    }
29
30
    public function limit(string $limit): Select
31
    {
32
        if (!empty($limit)) {
33
            $this->limit = $limit;
34
        }
35
        return $this;
36
    }
37
38
    public function order(string $order): Select
39
    {
40
        if (!empty($order)) {
41
            $this->order = $order;
0 ignored issues
show
Bug Best Practice introduced by
The property order does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
42
        }
43
        return $this;
44
    }
45
46
    public function calcFoundRows(): Select
47
    {
48
        $this->calcFoundRows = true;
49
        return $this;
50
    }
51
52
    public function __toString(): string
53
    {
54
        $expression = ($this->calcFoundRows ? 'SQL_CALC_FOUND_ROWS ' : '') . $this->expression;
55
56
        if (isset($this->tableAlias)) {
57
            $from = sprintf('`%s` AS `%s`', $this->table, $this->tableAlias);
58
        } else {
59
            $from = sprintf('`%s`', $this->table);
60
        }
61
62
        $limit = isset($this->limit) ? ' LIMIT '.$this->limit : '';
63
        $where = isset($this->where) ? ' WHERE ('.$this->where.')' : '';
64
        $having = isset($this->having) ? ' HAVING ('.$this->having.')' : '';
65
        $order = isset($this->order) ? ' ORDER BY '.$this->order : '';
66
67
        return sprintf('SELECT %s FROM %s %s %s %s %s', $expression, $from, $where, $having, $order, $limit);
68
    }
69
}
70