1 | <?php |
||
26 | class SqlSource extends AbstractSource |
||
27 | { |
||
28 | /** |
||
29 | * Set SQL source |
||
30 | * |
||
31 | * @param string $source |
||
32 | * |
||
33 | * @return void |
||
34 | * @throws \Bluz\Grid\GridException |
||
35 | */ |
||
36 | 2 | public function setSource($source) : void |
|
43 | |||
44 | /** |
||
45 | * {@inheritdoc} |
||
46 | */ |
||
47 | 1 | public function process(int $page, int $limit, array $filters = [], array $orders = []) : Data |
|
48 | { |
||
49 | // process filters |
||
50 | 1 | $filters = $this->applyFilters($filters); |
|
51 | |||
52 | // process orders |
||
53 | 1 | $orders = $this->applyOrders($orders); |
|
54 | |||
55 | // prepare query |
||
56 | 1 | $type = Proxy\Db::getOption('connect', 'type'); |
|
57 | |||
58 | 1 | if (strtolower($type) === 'mysql') { |
|
59 | // MySQL |
||
60 | 1 | $dataSql = preg_replace('/SELECT\s(.*?)\sFROM/is', 'SELECT SQL_CALC_FOUND_ROWS $1 FROM', $this->source, 1); |
|
61 | 1 | $totalSql = 'SELECT FOUND_ROWS()'; |
|
62 | } else { |
||
63 | // other |
||
64 | $dataSql = $this->source; |
||
65 | $totalSql = preg_replace('/SELECT\s(.*?)\sFROM/is', 'SELECT COUNT(*) FROM', $this->source, 1); |
||
66 | if (count($filters)) { |
||
67 | $totalSql .= ' WHERE ' . implode(' AND ', $filters); |
||
68 | } |
||
69 | } |
||
70 | |||
71 | 1 | if (count($filters)) { |
|
72 | 1 | $dataSql .= ' WHERE ' . implode(' AND ', $filters); |
|
73 | } |
||
74 | 1 | if (count($orders)) { |
|
75 | $dataSql .= ' ORDER BY ' . implode(', ', $orders); |
||
76 | } |
||
77 | // process pages |
||
78 | 1 | $dataSql .= ' LIMIT ' . ($page - 1) * $limit . ', ' . $limit; |
|
79 | |||
80 | // run queries |
||
81 | // use transaction to avoid errors |
||
82 | 1 | Proxy\Db::transaction( |
|
83 | function () use (&$data, &$total, $dataSql, $totalSql) { |
||
84 | 1 | $data = Proxy\Db::fetchAll($dataSql); |
|
85 | 1 | $total = (int)Proxy\Db::fetchOne($totalSql); |
|
86 | 1 | } |
|
87 | ); |
||
88 | |||
89 | 1 | $gridData = new Data($data); |
|
90 | 1 | $gridData->setTotal($total); |
|
91 | 1 | return $gridData; |
|
92 | } |
||
93 | |||
94 | /** |
||
95 | * Apply filters to SQL query |
||
96 | * |
||
97 | * @param array[] $settings |
||
98 | * |
||
99 | * @return array |
||
100 | */ |
||
101 | 1 | private function applyFilters(array $settings) : array |
|
116 | |||
117 | /** |
||
118 | * Apply order to SQL query |
||
119 | * |
||
120 | * @param array $settings |
||
121 | * |
||
122 | * @return array |
||
123 | */ |
||
124 | 1 | private function applyOrders(array $settings) : array |
|
134 | } |
||
135 |