PageParameterUrlBuilder::createPager()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
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 PageParameterUrlBuilder 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 $pageNumberQueryParam;
29
30
    /**
31
     * PageUrlBuilder constructor.
32
     * @param string $baseUrl
33
     * @param int    $perPage
34
     * @param string $pageNumberQueryParam
35
     */
36
    public function __construct(string $baseUrl, int $perPage, string $pageNumberQueryParam = 'page')
37
    {
38
        $this->baseUrl = $baseUrl;
39
        $this->perPage = max(0, $perPage);
40
        $this->pageNumberQueryParam = $pageNumberQueryParam;
41
    }
42
43
    /**
44
     * Return the current page.
45
     *
46
     * @return int
47
     */
48
    private function getCurrentPageNumber(): int
49
    {
50
        return query_string(uri($this->baseUrl))->getParam($this->pageNumberQueryParam) ?? 1;
51
    }
52
53
    /**
54
     * @inheritDoc
55
     */
56
    public function buildUrl(PagerInterface $pager, PageInterface $page): string
57
    {
58
        $uri = uri($this->baseUrl);
59
        $qs = query_string($uri->getQuery());
60
61
        return (string) $uri->withQuery(
62
            (string) $qs->withParam(
63
                $this->pageNumberQueryParam,
64
                $page->getPageNumber()
65
            )
66
        );
67
    }
68
69
    /**
70
     * @param int    $perPage
71
     * @param string $pageNumberQueryParam
72
     * @return PageParameterUrlBuilder
73
     * @throws \RuntimeException
74
     */
75
    public static function fromRequestUri(int $perPage, string $pageNumberQueryParam = 'page'): self
76
    {
77
        if (!isset($_SERVER['REQUEST_URI'])) {
78
            throw new \RuntimeException('$_SERVER[\'REQUEST_URI\'] is not set.');
79
        }
80
        return new static($_SERVER['REQUEST_URI'], $perPage, $pageNumberQueryParam);
81
    }
82
83
    /**
84
     * @param int|null $numFound
85
     * @return PagerInterface
86
     */
87
    public function createPager(int $numFound = null): PagerInterface
88
    {
89
        $pager = new Pager($this->perPage, $this->getCurrentPageNumber(), $numFound, $this);
90
        return $pager;
91
    }
92
}
93