OffsetParameterUrlBuilder::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
1
<?php
2
3
namespace BenTools\Pager\Model\Factory;
4
5
use BenTools\Pager\Contract\PageInterface;
6
use BenTools\Pager\Contract\PagerFactoryInterface;
7
use BenTools\Pager\Contract\PagerInterface;
8
use BenTools\Pager\Contract\PageUrlBuilderInterface;
9
use BenTools\Pager\Model\Pager;
10
use function BenTools\QueryString\query_string;
11
use function BenTools\UriFactory\Helper\uri;
12
13
class OffsetParameterUrlBuilder implements PageUrlBuilderInterface, PagerFactoryInterface
14
{
15
    /**
16
     * @var string
17
     */
18
    private $baseUrl;
19
20
    /**
21
     * @var int
22
     */
23
    private $perPage;
24
25
    /**
26
     * @var string
27
     */
28
    private $offsetQueryParam;
29
30
    /**
31
     * PageUrlBuilder constructor.
32
     * @param string $baseUrl
33
     * @param int    $perPage
34
     * @param string $offsetQueryParam
35
     */
36
    public function __construct(string $baseUrl, int $perPage, string $offsetQueryParam)
37
    {
38
        $this->baseUrl = $baseUrl;
39
        $this->perPage = max(0, $perPage);
40
        $this->offsetQueryParam = $offsetQueryParam;
41
    }
42
43
    /**
44
     * @inheritDoc
45
     */
46
    private function getCurrentPageNumber(): int
47
    {
48
        $qs = query_string(uri($this->baseUrl));
49
        $currentOffset = (int) max(0, $qs->getParam($this->offsetQueryParam) ?? 0);
50
51
        return (int) floor($currentOffset / $this->perPage) + 1;
52
    }
53
54
    /**
55
     * @inheritDoc
56
     */
57
    public function buildUrl(PagerInterface $pager, PageInterface $page): string
58
    {
59
        $uri = uri($this->baseUrl);
60
        $qs = query_string($uri->getQuery());
61
62
        return (string) $uri->withQuery(
63
            (string) $qs->withParam(
64
                $this->offsetQueryParam,
65
                $pager->getPageOffset($page)
66
            )
67
        );
68
    }
69
70
    /**
71
     * @param int    $perPage
72
     * @param string $offsetParam
73
     * @return OffsetParameterUrlBuilder
74
     * @throws \RuntimeException
75
     */
76
    public static function fromRequestUri(int $perPage, string $offsetParam): self
77
    {
78
        if (!isset($_SERVER['REQUEST_URI'])) {
79
            throw new \RuntimeException('$_SERVER[\'REQUEST_URI\'] is not set.');
80
        }
81
        return new static($_SERVER['REQUEST_URI'], $perPage, $offsetParam);
82
    }
83
84
    /**
85
     * @param int|null $numFound
86
     * @return PagerInterface
87
     */
88
    public function createPager(int $numFound = null): PagerInterface
89
    {
90
        $pager = new Pager($this->perPage, $this->getCurrentPageNumber(), $numFound, $this);
91
        return $pager;
92
    }
93
}
94