Passed
Push — master ( 05e56c...b87687 )
by Alejandro
04:13
created

VisitsParams::determineItemsPerPage()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.1406

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 2
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
ccs 3
cts 4
cp 0.75
crap 3.1406
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Core\Model;
5
6
use Cake\Chronos\Chronos;
7
use Shlinkio\Shlink\Common\Util\DateRange;
8
9
final class VisitsParams
10
{
11
    private const FIRST_PAGE = 1;
12
    private const ALL_ITEMS = -1;
13
14
    /** @var null|DateRange */
15
    private $dateRange;
16
    /** @var int */
17
    private $page;
18
    /** @var int */
19
    private $itemsPerPage;
20
21 7
    public function __construct(?DateRange $dateRange = null, int $page = self::FIRST_PAGE, ?int $itemsPerPage = null)
22
    {
23 7
        $this->dateRange = $dateRange ?? new DateRange();
24 7
        $this->page = $page;
25 7
        $this->itemsPerPage = $this->determineItemsPerPage($itemsPerPage);
26
    }
27
28 7
    private function determineItemsPerPage(?int $itemsPerPage): int
29
    {
30 7
        if ($itemsPerPage !== null && $itemsPerPage < 0) {
31
            return self::ALL_ITEMS;
32
        }
33
34 7
        return $itemsPerPage ?? self::ALL_ITEMS;
35
    }
36
37 3
    public static function fromRawData(array $query): self
38
    {
39 3
        $startDate = self::getDateQueryParam($query, 'startDate');
40 3
        $endDate = self::getDateQueryParam($query, 'endDate');
41
42 3
        return new self(
43 3
            new DateRange($startDate, $endDate),
44 3
            (int) ($query['page'] ?? 1),
45 3
            isset($query['itemsPerPage']) ? (int) $query['itemsPerPage'] : null
46
        );
47
    }
48
49 3
    private static function getDateQueryParam(array $query, string $key): ?Chronos
50
    {
51 3
        return ! isset($query[$key]) || empty($query[$key]) ? null : Chronos::parse($query[$key]);
52
    }
53
54 1
    public function getDateRange(): DateRange
55
    {
56 1
        return $this->dateRange;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->dateRange could return the type null which is incompatible with the type-hinted return Shlinkio\Shlink\Common\Util\DateRange. Consider adding an additional type-check to rule them out.
Loading history...
57
    }
58
59 1
    public function getPage(): int
60
    {
61 1
        return $this->page;
62
    }
63
64 1
    public function getItemsPerPage(): int
65
    {
66 1
        return $this->itemsPerPage;
67
    }
68
}
69