QueryBuilder::buildLimitQuery()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 4
eloc 9
c 1
b 1
f 0
nc 6
nop 3
dl 0
loc 16
rs 9.9666
1
<?php
2
/**
3
 * The Query builder API.
4
 *
5
 * @author RN Kushwaha <[email protected]>
6
 * @since v0.0.1 <Date: 16th April, 2019>
7
 */
8
9
namespace Dolphin\Builders;
10
11
use Dolphin\Connections\Connection;
12
use \Exception;
13
14
/**
15
 * This class provides the mechanism to build the Queries.
16
 */
17
class QueryBuilder
18
{
19
    protected $whereAdded = false;
20
21
    public function queryPrefix($query)
22
    {
23
        return str_replace('#__', Connection::getPrefix(), $query);
24
    }
25
26
    public function getPrefix()
27
    {
28
        return Connection::getPrefix();
29
    }
30
31
    public function fetchType($fetchMode = 'FETCH_OBJ')
32
    {
33
        switch ($fetchMode) {
34
            case 'FETCH_ASSOC': $fetch = \PDO::FETCH_ASSOC; break;
35
            case 'FETCH_NUM': $fetch = \PDO::FETCH_NUM; break;
36
            case 'FETCH_BOTH': $fetch = \PDO::FETCH_BOTH; break;
37
            case 'FETCH_BOUND': $fetch = \PDO::FETCH_BOUND; break;
38
            case 'FETCH_CLASS': $fetch = \PDO::FETCH_CLASS; break;
39
            default: $fetch = \PDO::FETCH_OBJ;
40
        }
41
42
        return $fetch;
43
    }
44
45
    public function addAlias($tableName)
46
    {
47
        $tableAlias = '';
48
49
        if (stripos($tableName, ' as ') > 0) {
50
            $tblName = explode(' as ', $tableName);
51
            $tableAlias = ' AS '.$this->quote($tblName[1]);
52
            $tableName = $tblName[0];
53
        }
54
55
        return [$tableName, $tableAlias];
56
    }
57
58
    public function quote($field)
59
    {
60
        if (strpos($field, '.') !== false) {
61
            $field = str_replace('.', '`.`', $field);
62
        }
63
64
        return '`'.$field.'`';
65
    }
66
67
    public function enclose($field)
68
    {
69
        return "'".$field."'";
70
    }
71
72
    private function getQueryFields($fields, $tbl){
73
        $startQuery = join(', ', $fields);
74
        if (empty($fields)) {
75
            $startQuery = $this->quote($tbl).'.*';
76
        }
77
78
        return $startQuery;
79
    }
80
81
    private function buildLimitQuery($limit, $offset, $query = []){
82
      $limitQuery = [];
83
      if (!empty($limit)) {
84
          $query[] = 'LIMIT';
85
86
          if (!empty($offset)) {
87
              $query[] = $offset.',';
88
          }
89
90
          $query[] = $limit;
91
      }
92
93
      if (count($limitQuery)) {
94
          $query = array_merge($query, $limitQuery);
95
      }
96
      return $query;
97
    }
98
99
    public function query($query, $fetchRows){
100
      try {
101
          $obj = Connection::get()->query($this->queryPrefix($query), \PDO::FETCH_OBJ);
102
103
          if ($fetchRows == 'count') {
104
              $obj = $obj->fetchColumn();
105
          }
106
107
          return $obj;
108
      } catch (\PDOException $ex) {
109
          throw new \PDOException($ex->getMessage(), 1);
110
      } catch (Exception $e) {
111
          throw new Exception($e->getMessage(), 1);
112
      }
113
    }
114
115
    public function buildQuery(array $params)
116
    {
117
        $jqb    = new JoinQueryBuilder();
118
        $wqb    = new WhereQueryBuilder();
119
120
        $prefix = $this->getPrefix();
121
        $tblWithPrefix = $params['table'];
122
        $tbl    = str_replace($prefix, '', $tblWithPrefix);
123
        $query  = [];
124
125
        $query[] = 'SELECT';
126
        $query[] = $this->getQueryFields($params['fields'], $tbl);
127
        $query[] = 'FROM';
128
        $query[] = $this->quote($tblWithPrefix).' AS '.$this->quote($tbl);
129
130
        $query = $jqb->buildAllJoinQuery(
131
                                $params['join'],
132
                                $params['leftJoin'],
133
                                $params['rightJoin'],
134
                                $params['crossJoin'],
135
                                $query
136
                            );
137
138
        $query = $wqb->buildAllWhereQuery(
139
                                    $params['where'],
140
                                    $params['whereRaw'],
141
                                    $params['whereIn'],
142
                                    $params['whereNotIn'],
143
                                    $params['whereNull'],
144
                                    $params['whereNotNull'],
145
                                    $query
146
                                );
147
148
        if (!empty($params['groupBy'])) {
149
            $query[] = 'GROUP BY';
150
            $query[] = $params['groupBy'];
151
        }
152
153
        if (!empty($params['having'])) {
154
            $query[] = 'HAVING';
155
            $query[] = $params['having'];
156
        }
157
158
        if (!empty($params['orderBy'])) {
159
            $query[] = 'ORDER BY';
160
            $query[] = $params['orderBy'];
161
        }
162
163
        $query = $this->buildLimitQuery($params['limit'], $params['offset'], $query);
164
165
        return $query;
166
    }
167
168
    public function getFields(array $args, bool $quote = true): array{
169
        $fldAr = [];
170
171
        foreach ($args as $arg) {
172
            foreach (explode(',', $arg) as $ar) {
173
                $fldAr[] = ($quote === true) ? $this->quote(trim($ar)) : trim($ar);
174
            }
175
        }
176
177
        return $fldAr;
178
    }
179
}
180