Completed
Push — master ( 597293...345e29 )
by Joao
04:12 queued 02:23
created

Query::build()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 16
cts 16
cp 1
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 16
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: jg
5
 * Date: 21/06/16
6
 * Time: 12:01
7
 */
8
9
namespace ByJG\MicroOrm;
10
11
use ByJG\AnyDataset\DbDriverInterface;
12
use ByJG\Serializer\BinderObject;
13
14
class Query
15
{
16
    protected $fields = [];
17
    protected $table = "";
18
    protected $where = [];
19
    protected $groupBy = [];
20
    protected $orderBy = [];
21
    protected $join = [];
22
    protected $limitStart = null;
23
    protected $limitEnd = null;
24
    protected $top = null;
25
26
    protected $forUpdate = false;
27
28 6
    public static function getInstance()
29
    {
30 6
        return new Query();
31
    }
32
33
    /**
34
     * Example:
35
     *   $query->fields(['name', 'price']);
36
     *
37
     * @param array $fields
38
     * @return $this
39
     * @throws \Exception
40
     */
41 5
    public function fields(array $fields)
42
    {
43 5
        foreach ($fields as $field) {
44 5
            if ($field instanceof Mapper) {
45 1
                $this->addFieldFromMapper($field);
46 1
                continue;
47
            }
48 4
            $this->fields[] = $field;
49 5
        }
50
51 5
        return $this;
52
    }
53
54
    /**
55
     * @param \ByJG\MicroOrm\Mapper $mapper
56
     * @throws \Exception
57
     */
58 1
    private function addFieldFromMapper(Mapper $mapper)
59
    {
60 1
        $entityClass = $mapper->getEntity();
61 1
        $entity = new $entityClass();
62 1
        $serialized = BinderObject::toArrayFrom($entity);
63
64 1
        foreach (array_keys($serialized) as $fieldName) {
65 1
            $mapField = $mapper->getFieldMap($fieldName, Mapper::FIELDMAP_FIELD);
66 1
            if (empty($mapField)) {
67 1
                $mapField = $fieldName;
68 1
            }
69
70 1
            $alias = $mapper->getFieldAlias($mapField);
71 1
            if (!empty($alias)) {
72 1
                $alias = ' as ' . $alias;
73 1
            }
74
75 1
            $this->fields[] = $mapper->getTable() . '.' . $mapField . $alias;
76 1
        }
77 1
    }
78
79
    /**
80
     * Example
81
     *    $query->table('product');
82
     *
83
     * @param string $table
84
     * @return $this
85
     */
86 24
    public function table($table)
87
    {
88 24
        $this->table = $table;
89
90 24
        return $this;
91
    }
92
93
    /**
94
     * Example:
95
     *    $query->join('sales', 'product.id = sales.id');
96
     *
97
     * @param string $table
98
     * @param string $filter
99
     * @return $this
100
     */
101 1
    public function join($table, $filter)
102
    {
103 1
        $this->join[] = [ 'table'=>$table, 'filter'=>$filter, 'type' => 'INNER'];
104 1
        return $this;
105
    }
106
107
    /**
108
     * Example:
109
     *    $query->join('sales', 'product.id = sales.id');
110
     *
111
     * @param string $table
112
     * @param string $filter
113
     * @return $this
114
     */
115 1
    public function leftJoin($table, $filter)
116
    {
117 1
        $this->join[] = [ 'table'=>$table, 'filter'=>$filter, 'type' => 'LEFT'];
118 1
        return $this;
119
    }
120
121
    /**
122
     * Example:
123
     *    $query->filter('price > [[amount]]', [ 'amount' => 1000] );
124
     *
125
     * @param string $filter
126
     * @param array $params
127
     * @return $this
128
     */
129 22
    public function where($filter, array $params = [])
130
    {
131 22
        $this->where[] = [ 'filter' => $filter, 'params' => $params  ];
132 22
        return $this;
133
    }
134
135
    /**
136
     * Example:
137
     *    $query->groupBy(['name']);
138
     *
139
     * @param array $fields
140
     * @return $this
141
     */
142 1
    public function groupBy(array $fields)
143
    {
144 1
        $this->groupBy = array_merge($this->groupBy, $fields);
145
    
146 1
        return $this;
147
    }
148
149
    /**
150
     * Example:
151
     *     $query->orderBy(['price desc']);
152
     *
153
     * @param array $fields
154
     * @return $this
155
     */
156 4
    public function orderBy(array $fields)
157
    {
158 4
        $this->orderBy = array_merge($this->orderBy, $fields);
159
160 4
        return $this;
161
    }
162
163
    public function forUpdate()
164
    {
165
        $this->forUpdate = true;
166
        
167
        return $this;
168
    }
169
170 1
    public function limit($start, $end)
171
    {
172 1
        if (!is_null($this->top)) {
173
            throw new \InvalidArgumentException('You cannot mix TOP and LIMIT');
174
        }
175 1
        $this->limitStart = $start;
176 1
        $this->limitEnd = $end;
177 1
        return $this;
178
    }
179
180 1
    public function top($top)
181
    {
182 1
        if (!is_null($this->limitStart)) {
183
            throw new \InvalidArgumentException('You cannot mix TOP and LIMIT');
184
        }
185 1
        $this->top = $top;
186 1
        return $this;
187
    }
188
189 24 View Code Duplication
    protected function getFields()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
190
    {
191 24
        if (empty($this->fields)) {
192 20
            return ' * ';
193
        }
194
195 5
        return ' ' . implode(', ', $this->fields) . ' ';
196
    }
197
    
198 24
    protected function getJoin()
199
    {
200 24
        $join = $this->table;
201 24
        foreach ($this->join as $item) {
202 2
            $join .= ' ' . $item['type'] . ' JOIN ' . $item['table'] . ' ON ' . $item['filter'];
203 24
        }
204 24
        return $join;
205
    }
206
    
207 24 View Code Duplication
    protected function getWhere()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
208
    {
209 24
        $where = [];
210 24
        $params = [];
211
212 24
        foreach ($this->where as $item) {
213 22
            $where[] = $item['filter'];
214 22
            $params = array_merge($params, $item['params']);
215 24
        }
216
        
217 24
        if (empty($where)) {
218 3
            return null;
219
        }
220
        
221 22
        return [ implode(' AND ', $where), $params ];
222
    }
223
224
    /**
225
     * @param \ByJG\AnyDataset\DbDriverInterface|null $dbDriver
226
     * @return array
227
     */
228 24
    public function build(DbDriverInterface $dbDriver = null)
229
    {
230
        $sql = "SELECT " .
231 24
            $this->getFields() .
232 24
            "FROM " . $this->getJoin();
233
        
234 24
        $where = $this->getWhere();
235 24
        $params = null;
236 24
        if (!is_null($where)) {
237 22
            $sql .= ' WHERE ' . $where[0];
238 22
            $params = $where[1];
239 22
        }
240
241 24
        $sql .= $this->addGroupBy();
242
243 24
        $sql .= $this->addOrderBy();
244
245 24
        $sql = $this->addforUpdate($dbDriver, $sql);
0 ignored issues
show
Bug introduced by
It seems like $dbDriver defined by parameter $dbDriver on line 228 can be null; however, ByJG\MicroOrm\Query::addforUpdate() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
246
247 24
        $sql = $this->addTop($dbDriver, $sql);
0 ignored issues
show
Bug introduced by
It seems like $dbDriver defined by parameter $dbDriver on line 228 can be null; however, ByJG\MicroOrm\Query::addTop() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
248
249 24
        $sql = $this->addLimit($dbDriver, $sql);
0 ignored issues
show
Bug introduced by
It seems like $dbDriver defined by parameter $dbDriver on line 228 can be null; however, ByJG\MicroOrm\Query::addLimit() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
250
251 24
        $sql = ORMHelper::processLiteral($sql, $params);
252
253 24
        return [ 'sql' => $sql, 'params' => $params ];
254
    }
255
256 24
    private function addOrderBy()
257
    {
258 24
        if (empty($this->orderBy)) {
259 21
            return "";
260
        }
261 4
        return ' ORDER BY ' . implode(', ', $this->orderBy);
262
    }
263
264 24
    private function addGroupBy()
265
    {
266 24
        if (empty($this->groupBy)) {
267 24
            return "";
268
        }
269 1
        return ' GROUP BY ' . implode(', ', $this->groupBy);
270
    }
271
272
    /**
273
     * @param DbDriverInterface $dbDriver
274
     * @param string $sql
275
     * @return string
276
     */
277 24 View Code Duplication
    private function addforUpdate($dbDriver, $sql)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
278
    {
279 24
        if (empty($this->forUpdate)) {
280 24
            return $sql;
281
        }
282
283
        if (is_null($dbDriver)) {
284
            throw new \InvalidArgumentException('To get FOR UPDATE working you have to pass the DbDriver');
285
        }
286
287
        return $dbDriver->getDbHelper()->forUpdate($sql);
288
    }
289
290
    /**
291
     * @param DbDriverInterface $dbDriver
292
     * @param string $sql
293
     * @return string
294
     */
295 24 View Code Duplication
    private function addTop($dbDriver, $sql)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
296
    {
297 24
        if (empty($this->top)) {
298 23
            return $sql;
299
        }
300
301 1
        if (is_null($dbDriver)) {
302
            throw new \InvalidArgumentException('To get Limit and Top working you have to pass the DbDriver');
303
        }
304
305 1
        return $dbDriver->getDbHelper()->top($sql, $this->top);
306
    }
307
308
    /**
309
     * @param DbDriverInterface $dbDriver
310
     * @param string $sql
311
     * @return string
312
     */
313 24
    private function addLimit($dbDriver, $sql)
314
    {
315 24
        if (empty($this->limitStart) && ($this->limitStart !== 0)) {
316 23
            return $sql;
317
        }
318
319 1
        if (is_null($dbDriver)) {
320
            throw new \InvalidArgumentException('To get Limit and Top working you have to pass the DbDriver');
321
        }
322
323 1
        return $dbDriver->getDbHelper()->limit($sql, $this->limitStart, $this->limitEnd);
324
    }
325
}
326