Passed
Push — master ( 30befd...b79908 )
by RN
01:57
created

QueryBuilder   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 148
Duplicated Lines 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 79
dl 0
loc 148
rs 10
c 3
b 1
f 0
wmc 27

10 Methods

Rating   Name   Duplication   Size   Complexity  
A getPrefix() 0 3 1
A fetchType() 0 12 6
A queryPrefix() 0 3 1
A addAlias() 0 11 2
A quote() 0 7 2
A getQueryFields() 0 7 2
A enclose() 0 3 1
A buildLimitQuery() 0 16 4
A query() 0 13 4
A buildQuery() 0 51 4
1
<?php
2
/**
3
 * The Query builder API.
4
 *
5
 * @author RN Kushwaha <[email protected]>
6
 *
7
 * @since v0.0.1 <Date: 16th April, 2019>
8
 */
9
10
namespace Dolphin\Builders;
11
12
use Dolphin\Connections\Connection;
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 '.self::quote($tblName[1]);
0 ignored issues
show
Bug Best Practice introduced by
The method Dolphin\Builders\QueryBuilder::quote() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

51
            $tableAlias = ' AS '.self::/** @scrutinizer ignore-call */ quote($tblName[1]);
Loading history...
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
    public function enclose($field)
67
    {
68
        return "'".$field."'";
69
    }
70
71
    private function getQueryFields($fields, $tbl){
72
        $startQuery = join(', ', $fields);
73
        if (empty($fields)) {
74
            $startQuery = $this->quote($tbl).'.*';
75
        }
76
77
        return $startQuery;
78
    }
79
80
    private function buildLimitQuery($limit, $offset, $query = array()){
81
      $limitQuery = [];
82
      if (!empty($limit)) {
83
          $query[] = 'LIMIT';
84
85
          if (!empty($offset)) {
86
              $query[] = $offset.',';
87
          }
88
89
          $query[] = $limit;
90
      }
91
92
      if (count($limitQuery)) {
93
          $query = array_merge($query, $limitQuery);
94
      }
95
      return $query;
96
    }
97
98
    public function query($query, $fetchRows){
99
      try {
100
          $obj = Connection::get()->query($this->queryPrefix($query), \PDO::FETCH_OBJ);
101
102
          if ($fetchRows == 'count') {
103
              $obj = $obj->fetchColumn();
104
          }
105
106
          return $obj;
107
      } catch (\PDOException $ex) {
108
          throw new \PDOException($ex->getMessage(), 1);
109
      } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The type Dolphin\Builders\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
110
          throw new Exception($e->getMessage(), 1);
111
      }
112
    }
113
114
    public function buildQuery(array $params)
115
    {
116
        $jqb    = new JoinQueryBuilder();
117
        $wqb    = new WhereQueryBuilder();
118
119
        $prefix = $this->getPrefix();
120
        $tblWithPrefix = $params['table'];
121
        $tbl    = str_replace($prefix, '', $tblWithPrefix);
122
        $query  = [];
123
124
        $query[] = 'SELECT';
125
        $query[] = $this->getQueryFields($params['fields'], $tbl);
126
        $query[] = 'FROM';
127
        $query[] = $this->quote($tblWithPrefix).' AS '.$this->quote($tbl);
128
129
        $query = $jqb->buildAllJoinQuery(
130
                                $params['join'],
131
                                $params['leftJoin'],
132
                                $params['rightJoin'],
133
                                $params['crossJoin'],
134
                                $query
135
                            );
136
137
        $query = $wqb->buildAllWhereQuery(
138
                                    $params['where'],
139
                                    $params['whereRaw'],
140
                                    $params['whereIn'],
141
                                    $params['whereNotIn'],
142
                                    $params['whereNull'],
143
                                    $params['whereNotNull'],
144
                                    $query
145
                                );
146
147
        if (!empty($params['groupBy'])) {
148
            $query[] = 'GROUP BY';
149
            $query[] = $params['groupBy'];
150
        }
151
152
        if (!empty($params['having'])) {
153
            $query[] = 'HAVING';
154
            $query[] = $params['having'];
155
        }
156
157
        if (!empty($params['orderBy'])) {
158
            $query[] = 'ORDER BY';
159
            $query[] = $params['orderBy'];
160
        }
161
162
        $query = $this->buildLimitQuery($params['limit'], $params['offset'], $query);
163
164
        return $query;
165
    }
166
}
167