|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace HexMakina\TightORM; |
|
4
|
|
|
|
|
5
|
|
|
use HexMakina\BlackBox\ORM\ModelInterface; |
|
6
|
|
|
use HexMakina\BlackBox\Database\SelectInterface; |
|
7
|
|
|
|
|
8
|
|
|
class TableModelSelector |
|
9
|
|
|
{ |
|
10
|
|
|
private $class; |
|
11
|
|
|
private $table; |
|
12
|
|
|
private $query; |
|
13
|
|
|
|
|
14
|
|
|
public function __construct(string $class) |
|
15
|
|
|
{ |
|
16
|
|
|
if(class_exists($class) === false) |
|
17
|
|
|
throw new \Exception('CLASS_NOT_FOUND'); |
|
18
|
|
|
|
|
19
|
|
|
$this->class = $class; |
|
20
|
|
|
$this->table = $this->class::table(); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
public function select($filters = [], $options = []): SelectInterface |
|
24
|
|
|
{ |
|
25
|
|
|
$this->query = $this->table->select(null, $options['table_alias'] ?? $this->class::tableAlias()); |
|
26
|
|
|
|
|
27
|
|
|
// if the array of filters contains an index macthing a column name, it is used as a EQ filter |
|
28
|
|
|
// it is used as a where equal clause |
|
29
|
|
|
foreach (array_keys($this->table->columns()) as $column_name) { |
|
30
|
|
|
if (isset($filters[$column_name]) && is_scalar($filters[$column_name])) { |
|
31
|
|
|
|
|
32
|
|
|
$this->query->whereEQ($column_name, $filters[$column_name]); |
|
33
|
|
|
|
|
34
|
|
|
unset($filters[$column_name]); |
|
35
|
|
|
} |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
// now that the possibility of index matching columns is removed, |
|
39
|
|
|
// the rest of the array is used as a filter shortcuts |
|
40
|
|
|
|
|
41
|
|
|
// shortcut 'ids' => [1,2,3] is used as a where in clause |
|
42
|
|
|
if (isset($filters['ids'])) { |
|
43
|
|
|
$this->filterByIds($filters['ids']); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
// shortcut 'content' |
|
47
|
|
|
if (isset($filters['content'])) { |
|
48
|
|
|
$this->query->whereFilterContent($filters['content']); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
|
|
52
|
|
|
// processing options |
|
53
|
|
|
if (isset($options['order_by'])) { |
|
54
|
|
|
$this->query->orderBy($options['order_by']); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
if (isset($options['limit'])) { |
|
58
|
|
|
// if limit is an array, it is used as [$limit, $offset] |
|
59
|
|
|
// else, it is used as [$limit, 0] |
|
60
|
|
|
[$limit, $offset] = is_array($options['limit']) ? $options['limit'] : [$options['limit'], 0]; |
|
61
|
|
|
|
|
62
|
|
|
$this->query->limit($limit, $offset); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
|
|
66
|
|
|
return $this->query; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
private function filterByIds(array $ids) |
|
70
|
|
|
{ |
|
71
|
|
|
|
|
72
|
|
|
if (empty($ids)) { |
|
73
|
|
|
// as a security, if array is empty, |
|
74
|
|
|
// the query is cancelled by setting the limit to 0 |
|
75
|
|
|
$this->query->limit(0); |
|
76
|
|
|
} else { |
|
77
|
|
|
$this->query->whereNumericIn('id', $ids, $this->query->tableLabel()); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|