Completed
Pull Request — 2.x (#99)
by Hari
07:29 queued 05:28
created

AbstractQuery::buildLimit()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 20
ccs 10
cts 10
cp 1
rs 8.8571
cc 6
eloc 11
nc 32
nop 0
crap 6
1
<?php
2
/**
3
 *
4
 * This file is part of Aura for PHP.
5
 *
6
 * @license http://opensource.org/licenses/bsd-license.php BSD
7
 *
8
 */
9
namespace Aura\SqlQuery;
10
11
use Aura\SqlQuery\Common\LimitInterface;
12
use Aura\SqlQuery\Common\LimitOffsetInterface;
13
use Aura\SqlQuery\Common\SubselectInterface;
14
15
/**
16
 *
17
 * Abstract query object.
18
 *
19
 * @package Aura.SqlQuery
20
 *
21
 */
22
abstract class AbstractQuery
23
{
24
    /**
25
     *
26
     * Data to be bound to the query.
27
     *
28
     * @var array
29
     *
30
     */
31
    protected $bind_values = array();
32
33
    /**
34
     *
35
     * The list of WHERE conditions.
36
     *
37
     * @var array
38
     *
39
     */
40
    protected $where = array();
41
42
    /**
43
     *
44
     * ORDER BY these columns.
45
     *
46
     * @var array
47
     *
48
     */
49
    protected $order_by = array();
50
51
    /**
52
     *
53
     * The number of rows to select
54
     *
55
     * @var int
56
     *
57
     */
58
    protected $limit = 0;
59
60
    /**
61
     *
62
     * Return rows after this offset.
63
     *
64
     * @var int
65
     *
66
     */
67
    protected $offset = 0;
68
69
    /**
70
     *
71
     * The list of flags.
72
     *
73
     * @var array
74
     *
75
     */
76
    protected $flags = array();
77
78
    /**
79
     *
80
     * A helper for quoting identifier names.
81
     *
82
     * @var Quoter
83
     *
84
     */
85
    protected $quoter;
86
87
    /**
88
     *
89
     * Prefix to use on placeholders for "sequential" bound values; used for
90
     * deconfliction when merging bound values from sub-selects, etc.
91
     *
92
     * @var mixed
93
     *
94
     */
95
    protected $seq_bind_prefix = '';
96
97
    /**
98
     *
99
     * Constructor.
100
     *
101
     * @param Quoter $quoter A helper for quoting identifier names.
102
     *
103
     * @param string $seq_bind_prefix A prefix for rewritten sequential-binding
104
     * placeholders (@see getSeqPlaceholder()).
105
     *
106
     */
107 376
    public function __construct(Quoter $quoter, $seq_bind_prefix = '')
108
    {
109 376
        $this->quoter = $quoter;
110 376
        $this->seq_bind_prefix = $seq_bind_prefix;
111
    }
112
113
    /**
114
     *
115
     * Returns the prefix for rewritten sequential-binding placeholders
116
     * (@see getSeqPlaceholder()).
117
     *
118
     * @return string
119
     *
120
     */
121
    public function getSeqBindPrefix()
122
    {
123
        return $this->seq_bind_prefix;
124
    }
125
126
    /**
127
     *
128
     * Returns this query object as an SQL statement string.
129
     *
130
     * @return string
131
     *
132
     */
133 5
    public function __toString()
134
    {
135 5
        return $this->getStatement();
136
    }
137
138
    /**
139
     *
140
     * Returns this query object as an SQL statement string.
141
     *
142
     * @return string
143
     *
144
     */
145
    public function getStatement()
146
    {
147
        return $this->build();
148
    }
149
150
    /**
151
     *
152
     * Builds this query object into a string.
153
     *
154
     * @return string
155
     *
156
     */
157
    abstract protected function build();
158
159
    /**
160
     *
161
     * Returns the prefix to use when quoting identifier names.
162
     *
163
     * @return string
164
     *
165
     */
166
    public function getQuoteNamePrefix()
167
    {
168
        return $this->quoter->getQuoteNamePrefix();
169
    }
170
171
    /**
172
     *
173
     * Returns the suffix to use when quoting identifier names.
174
     *
175
     * @return string
176
     *
177
     */
178
    public function getQuoteNameSuffix()
179
    {
180
        return $this->quoter->getQuoteNameSuffix();
181
    }
182
183
    /**
184
     *
185
     * Returns an array as an indented comma-separated values string.
186
     *
187
     * @param array $list The values to convert.
188
     *
189
     * @return string
190
     *
191
     */
192 61
    protected function indentCsv(array $list)
193
    {
194 61
        return PHP_EOL . '    '
195
             . implode(',' . PHP_EOL . '    ', $list);
196 61
    }
197
198
    /**
199
     *
200
     * Returns an array as an indented string.
201
     *
202
     * @param array $list The values to convert.
203
     *
204
     * @return string
205
     *
206
     */
207 50
    protected function indent(array $list)
208
    {
209 50
        return PHP_EOL . '    '
210
             . implode(PHP_EOL . '    ', $list);
211 50
    }
212
213
    /**
214
     *
215
     * Binds multiple values to placeholders; merges with existing values.
216
     *
217
     * @param array $bind_values Values to bind to placeholders.
218
     *
219
     * @return $this
220
     *
221
     */
222 16
    public function bindValues(array $bind_values)
223
    {
224
        // array_merge() renumbers integer keys, which is bad for
225
        // question-mark placeholders
226
        foreach ($bind_values as $key => $val) {
227
            $this->bindValue($key, $val);
228
        }
229 16
        return $this;
230 16
    }
231
232
    /**
233
     *
234
     * Binds a single value to the query.
235
     *
236
     * @param string $name The placeholder name or number.
237
     *
238
     * @param mixed $value The value to bind to the placeholder.
239
     *
240
     * @return $this
241
     *
242
     */
243 21
    public function bindValue($name, $value)
244
    {
245 21
        $this->bind_values[$name] = $value;
246 21
        return $this;
247
    }
248
249
    /**
250
     *
251
     * Gets the values to bind to placeholders.
252
     *
253
     * @return array
254
     *
255
     */
256 106
    public function getBindValues()
257
    {
258 106
        return $this->bind_values;
259
    }
260
261
    /**
262
     *
263
     * Builds the flags as a space-separated string.
264
     *
265
     * @return string
266
     *
267
     */
268 212
    protected function buildFlags()
269
    {
270 212
        if (! $this->flags) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->flags of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
271 174
            return ''; // not applicable
272
        }
273
274
        return ' ' . implode(' ', array_keys($this->flags));
275
    }
276
277
    /**
278
     *
279
     * Sets or unsets specified flag.
280
     *
281
     * @param string $flag Flag to set or unset
282
     *
283
     * @param bool $enable Flag status - enabled or not (default true)
284
     *
285
     * @return null
286
     *
287
     */
288 37
    protected function setFlag($flag, $enable = true)
289
    {
290 32
        if ($enable) {
291 37
            $this->flags[$flag] = true;
292
        } else {
293 5
            unset($this->flags[$flag]);
294 37
        }
295 32
    }
296
297
    /**
298
     *
299
     * Reset all query flags.
300
     *
301
     * @return null
302
     *
303
     */
304 15
    protected function resetFlags()
305
    {
306 15
        $this->flags = array();
307 15
    }
308
309
    /**
310
     *
311
     * Adds a WHERE condition to the query by AND or OR. If the condition has
312
     * ?-placeholders, additional arguments to the method will be bound to
313
     * those placeholders sequentially.
314
     *
315
     * @param string $andor Add the condition using this operator, typically
316
     * 'AND' or 'OR'.
317
     *
318
     * @param array $args Arguments for adding the condition.
319
     *
320
     * @return $this
321
     *
322
     */
323 11
    protected function addWhere($andor, $args)
324
    {
325
        $this->addClauseCondWithBind('where', $andor, $args);
326 11
        return $this;
327
    }
328
329
    /**
330
     *
331
     * Adds conditions and binds values to a clause.
332
     *
333
     * @param string $clause The clause to work with, typically 'where' or
334
     * 'having'.
335
     *
336
     * @param string $andor Add the condition using this operator, typically
337
     * 'AND' or 'OR'.
338
     *
339
     * @param array $args Arguments for adding the condition.
340
     *
341
     * @return null
342
     *
343
     */
344 50
    protected function addClauseCondWithBind($clause, $andor, $args)
345
    {
346
        // remove the condition from the args and quote names in it
347
        $cond = array_shift($args);
348
        $cond = $this->rebuildCondAndBindValues($cond, $args);
349
350
        // add condition to clause; $this->where
351 6
        $clause =& $this->$clause;
352 6
        if ($clause) {
353 25
            $clause[] = "$andor $cond";
354
        } else {
355 50
            $clause[] = $cond;
356 25
        }
357 6
    }
358
359
    /**
360
     *
361
     * Rebuilds a condition string, replacing sequential placeholders with
362
     * named placeholders, and binding the sequential values to the named
363
     * placeholders.
364
     *
365
     * @param string $cond The condition with sequential placeholders.
366
     *
367
     * @param array $bind_values The values to bind to the sequential
368
     * placeholders under their named versions.
369
     *
370
     * @return string The rebuilt condition string.
371
     *
372
     */
373 31
    protected function rebuildCondAndBindValues($cond, array $bind_values)
374
    {
375
        $cond = $this->quoter->quoteNamesIn($cond);
376
377
        // bind values against ?-mark placeholders, but because PDO is finicky
378
        // about the numbering of sequential placeholders, convert each ?-mark
379
        // to a named placeholder
380
        $parts = preg_split('/(\?)/', $cond, null, PREG_SPLIT_DELIM_CAPTURE);
381
        foreach ($parts as $key => $val) {
382 10
            if ($val != '?') {
383 10
                continue;
384
            }
385
386
            $bind_value = array_shift($bind_values);
387 31
            if ($bind_value instanceof SubselectInterface) {
388
                $parts[$key] = $bind_value->getStatement();
389 10
                $this->bind_values = array_merge(
390 10
                    $this->bind_values,
391 10
                    $bind_value->getBindValues()
392
                );
393 10
                continue;
394
            }
395
396
            $placeholder = $this->getSeqPlaceholder();
397 26
            $parts[$key] = ':' . $placeholder;
398 26
            $this->bind_values[$placeholder] = $bind_value;
399
        }
400
401
        $cond = implode('', $parts);
402 21
        return $cond;
403 21
    }
404
405
    /**
406
     *
407
     * Gets the current sequential placeholder name.
408
     *
409
     * @return string
410
     *
411
     */
412 26
    protected function getSeqPlaceholder()
413
    {
414
        $i = count($this->bind_values) + 1;
415 26
        return $this->seq_bind_prefix . "_{$i}_";
416
    }
417
418
    /**
419
     *
420
     * Builds the `WHERE` clause of the statement.
421
     *
422
     * @return string
423
     *
424
     */
425 166
    protected function buildWhere()
426
    {
427 166
        if (! $this->where) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->where of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
428 126
            return ''; // not applicable
429
        }
430
431
        return PHP_EOL . 'WHERE' . $this->indent($this->where);
432
    }
433
434
    /**
435
     *
436
     * Adds a column order to the query.
437
     *
438
     * @param array $spec The columns and direction to order by.
439
     *
440
     * @return $this
441
     *
442
     */
443 9
    protected function addOrderBy(array $spec)
444
    {
445
        foreach ($spec as $col) {
446
            $this->order_by[] = $this->quoter->quoteNamesIn($col);
447
        }
448 9
        return $this;
449 9
    }
450
451
    /**
452
     *
453
     * Builds the `ORDER BY ...` clause of the statement.
454
     *
455
     * @return string
456
     *
457
     */
458 166
    protected function buildOrderBy()
459
    {
460 166
        if (! $this->order_by) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->order_by of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
461 157
            return ''; // not applicable
462
        }
463
464
        return PHP_EOL . 'ORDER BY' . $this->indentCsv($this->order_by);
465
    }
466
467
    /**
468
     *
469
     * Builds the `LIMIT ... OFFSET` clause of the statement.
470
     *
471
     * Note that this will allow OFFSET values with a LIMIT.
472
     *
473
     * @return string
474
     *
475
     */
476 140
    protected function buildLimit()
477
    {
478 140
        $clause = '';
479 140
        $limit = $this instanceof LimitInterface && $this->limit;
480 140
        $offset = $this instanceof LimitOffsetInterface && $this->offset;
481
482 140
        if ($limit) {
483 15
            $clause .= "LIMIT {$this->limit}";
484
        }
485
486 140
        if ($offset) {
487 10
            $clause .= " OFFSET {$this->offset}";
488
        }
489
490 140
        if ($clause) {
491
            $clause = PHP_EOL . trim($clause);
492
        }
493
494 140
        return $clause;
495
    }
496
}
497