Completed
Push — 3.x ( e5eb1c...76cecd )
by Paul
9s
created

SelectBuilder::buildLimitOffset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
crap 1
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\Sqlsrv;
10
11
use Aura\SqlQuery\Common;
12
13
/**
14
 *
15
 * An object for Sqlsrv SELECT queries.
16
 *
17
 * @package Aura.SqlQuery
18
 *
19
 */
20
class SelectBuilder extends Common\SelectBuilder
21
{
22
    /**
23
     *
24
     * Override so that LIMIT equivalent will be applied by applyLimit().
25
     *
26
     * @see build()
27
     *
28
     * @see applyLimit()
29
     *
30
     */
31 35
    public function buildLimitOffset($limit, $offset)
32
    {
33 35
        return '';
34
    }
35
36
    /**
37
     *
38
     * Modify the statement applying limit/offset equivalent portions to it.
39
     *
40
     * @param string $stm SQL statement
41
     * @return string SQL statement with limit/offset applied
42
     *
43
     */
44 35
    public function applyLimit($stm, $limit, $offset)
45
    {
46 35
        if (! $limit && ! $offset) {
47 33
            return $stm; // no limit or offset
48
        }
49
50
        // limit but no offset?
51 2
        if ($limit && ! $offset) {
52
            // use TOP in place
53 1
            return preg_replace(
54 1
                '/^(SELECT( DISTINCT)?)/',
55 1
                "$1 TOP {$limit}",
56
                $stm
57
            );
58
        }
59
60
        // both limit and offset. must have an ORDER clause to work; OFFSET is
61
        // a sub-clause of the ORDER clause. cannot use FETCH without OFFSET.
62 2
        return $stm . PHP_EOL . "OFFSET {$offset} ROWS "
63 2
                    . "FETCH NEXT {$limit} ROWS ONLY";
64
    }
65
}
66