LimitOffsetTrait::buildOffsetQueryPart()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
nc 2
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Janisbiz\LightOrm\Dms\MySQL\QueryBuilder\Traits;
4
5
use Janisbiz\LightOrm\Dms\MySQL\Enum\ConditionEnum;
6
use Janisbiz\LightOrm\Dms\MySQL\QueryBuilder\QueryBuilderException;
7
8
trait LimitOffsetTrait
9
{
10
    /**
11
     * @var null|int
12
     */
13
    protected $limit;
14
15
    /**
16
     * @var null|int
17
     */
18
    protected $offset;
19
20
    /**
21
     * @param int $limit
22
     *
23
     * @return $this
24
     * @throws QueryBuilderException
25
     */
26
    public function limit(int $limit)
27
    {
28
        if (0 >= $limit) {
29
            throw new QueryBuilderException('You must pass $limit to limit method!');
30
        }
31
32
        $this->limit = (int) $limit;
33
34
        return $this;
35
    }
36
37
    /**
38
     * @param int $offset
39
     *
40
     * @return $this
41
     * @throws QueryBuilderException
42
     */
43
    public function offset(int $offset)
44
    {
45
        if (0 > $offset) {
46
            throw new QueryBuilderException('You must pass $offset to offset method!');
47
        }
48
49
        if (empty($this->limit)) {
50
            throw new QueryBuilderException('You must set LIMIT before calling offset method!');
51
        }
52
53
        $this->offset = (int) $offset;
54
55
        return $this;
56
    }
57
58
    /**
59
     * @param int $limit
60
     * @param int $offset
61
     *
62
     * @return $this
63
     */
64
    public function limitWithOffset(int $limit, int $offset)
65
    {
66
        return $this->limit($limit)->offset($offset);
67
    }
68
69
    /**
70
     * @return null|string
71
     */
72
    protected function buildLimitQueryPart(): ?string
73
    {
74
        return empty($this->limit) ? null : \sprintf('%s %d', ConditionEnum::LIMIT, $this->limit);
75
    }
76
77
    /**
78
     * @return null|string
79
     */
80
    protected function buildOffsetQueryPart(): ?string
81
    {
82
        return empty($this->offset) ? null : \sprintf('%s %d', ConditionEnum::OFFSET, $this->offset);
83
    }
84
}
85