Completed
Push — resets ( d2f77b )
by Paul
02:06
created

Select::build()   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
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
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 Select extends Common\Select
21
{
22
    /**
23
     *
24
     * Builds this query object into a string.
25
     *
26
     * @return string
27
     *
28
     */
29 33
    protected function build()
30
    {
31 33
        return $this->applyLimit(parent::build());
32
    }
33
34
    /**
35
     *
36
     * Override so that LIMIT equivalent will be applied by applyLimit().
37
     *
38
     * @see build()
39
     *
40
     * @see applyLimit()
41
     *
42
     */
43 32
    protected function buildLimit()
44
    {
45 32
        return '';
46
    }
47
48
    /**
49
     *
50
     * Modify the statement applying limit/offset equivalent portions to it.
51
     *
52
     * @param string $stm SQL statement
53
     * @return string SQL statement with limit/offset applied
54
     *
55
     */
56 32
    protected function applyLimit($stm)
57
    {
58 32
        if (! $this->limit && ! $this->offset) {
59 30
            return $stm; // no limit or offset
60
        }
61
62
        // limit but no offset?
63 2
        if ($this->limit && ! $this->offset) {
64
            // use TOP in place
65 1
            return preg_replace(
66 1
                '/^(SELECT( DISTINCT)?)/',
67 1
                "$1 TOP {$this->limit}",
68
                $stm
69 1
            );
70
        }
71
72
        // both limit and offset. must have an ORDER clause to work; OFFSET is
73
        // a sub-clause of the ORDER clause. cannot use FETCH without OFFSET.
74 2
        return $stm . PHP_EOL . "OFFSET {$this->offset} ROWS "
75 2
                    . "FETCH NEXT {$this->limit} ROWS ONLY";
76
    }
77
}
78