Range   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Test Coverage

Coverage 55.56%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 58
ccs 10
cts 18
cp 0.5556
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A buildLimit() 0 5 3
A page() 0 11 3
A limit() 0 14 3
1
<?php
2
3
namespace mindplay\sql\model\components;
4
5
use InvalidArgumentException;
6
7
/**
8
 * This trait implements the `LIMIT` and `OFFSET` clause.
9
 */
10
trait Range
11
{
12
    protected int|null $limit = null;
13
    protected int|null $offset = null;
14
15
    /**
16
     * @param int      $limit  max. number of records
17
     * @param int|null $offset base-0 record number offset
18
     *
19
     * @return $this
20
     *
21
     * @throws InvalidArgumentException if the given limit is less than 1, or if the given offset if less than 0
22
     */
23 1
    public function limit(int|null $limit, int|null $offset = null): static
24
    {
25 1
        if ($limit < 1) {
26
            throw new InvalidArgumentException("limit out of range: {$limit}");
27
        }
28
29 1
        if ($offset < 0) {
30
            throw new InvalidArgumentException("offset out of range: {$offset}");
31
        }
32
33 1
        $this->limit = $limit;
34 1
        $this->offset = $offset;
35
36 1
        return $this;
37
    }
38
39
    /**
40
     * @param int $page_num  base-1 page number
41
     * @param int $page_size number of records per page
42
     *
43
     * @return $this
44
     *
45
     * @throws InvalidArgumentException if the given page number or page size are less than 1
46
     */
47 1
    public function page(int $page_num, int $page_size): static
48
    {
49 1
        if ($page_size < 1) {
50
            throw new InvalidArgumentException("page size out of range: {$page_size}");
51
        }
52
53 1
        if ($page_num < 1) {
54
            throw new InvalidArgumentException("page number out of range: {$page_num}");
55
        }
56
57 1
        return $this->limit($page_size, ($page_num - 1) * $page_size);
58
    }
59
60
    /**
61
     * @return string the LIMIT/OFFSET clause (or an empty string, if no limit has been set)
62
     */
63
    protected function buildLimit(): string
64
    {
65
        return $this->limit !== null
66
            ? "\nLIMIT {$this->limit}" . ($this->offset !== null ? " OFFSET {$this->offset}" : '')
67
            : ''; // no limit or offset
68
    }
69
}
70