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

LimitedRelationDefinition   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 33
c 0
b 0
f 0
wmc 6
lcom 1
cbo 2
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 3
A toSql() 0 10 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