Completed
Push — master ( bd03b7...2e6f46 )
by Ondřej
03:14
created

LimitedRelationRecipe::toSql()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 10
Code Lines 7

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