Completed
Push — master ( 509987...79a3d2 )
by Rasmus
02:45
created

Range   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 55.56%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 0
dl 0
loc 67
ccs 10
cts 18
cp 0.5556
rs 10
c 0
b 0
f 0

3 Methods

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