Passed
Push — master ( b2bdac...3a7f22 )
by Ondřej
03:22
created

LimitedRelationDefinition::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 6
nc 3
nop 3
1
<?php
2
namespace Ivory\Query;
3
4
use Ivory\Type\ITypeDictionary;
5
6
class LimitedRelationDefinition extends RelationDefinition implements IRelationDefinition
7
{
8
    private $baseRelDef;
9
    private $limit;
10
    private $offset;
11
12
    /**
13
     * @param IRelationDefinition $relationDefinition definition of relation to limit
14
     * @param int|null $limit maximal number of rows to return; <tt>null</tt> for unlimited number of rows
15
     * @param int $offset a non-negative offset - the number of original rows to skip
16
     */
17
    public function __construct(IRelationDefinition $relationDefinition, $limit, int $offset = 0)
18
    {
19
        if ($offset < 0) {
20
            throw new \InvalidArgumentException('$offset is negative');
21
        }
22
23
        $this->baseRelDef = $relationDefinition;
24
        $this->limit = ($limit !== null ? (int)$limit : null); // PHP 7.1: declare the type as ?int
25
        $this->offset = $offset;
26
    }
27
28
    public function toSql(ITypeDictionary $typeDictionary): string
29
    {
30
        $relSql = $this->baseRelDef->toSql($typeDictionary);
31
        return sprintf(
32
            "SELECT *\nFROM (\n%s\n) t%s%s",
33
            $relSql,
34
            ($this->limit !== null ? "\nLIMIT {$this->limit}" : ''),
35
            ($this->offset ? "\nOFFSET {$this->offset}" : '')
36
        );
37
    }
38
}
39