Completed
Push — master ( 8e0ccf...b79b3d )
by Anton
02:40
created

PaginationFactory::createPaginator()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 23
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 3
nop 2
dl 0
loc 23
rs 8.7972
c 0
b 0
f 0
1
<?php
2
/**
3
 * spiral
4
 *
5
 * @author    Wolfy-J
6
 */
7
8
namespace Spiral\Pagination;
9
10
use Psr\Http\Message\ServerRequestInterface;
11
use Spiral\Core\Container\SingletonInterface;
12
use Spiral\Core\ContainerInterface;
13
use Spiral\Core\Exceptions\ScopeException;
14
15
/**
16
 * Paginators factory binded to active request scope in order to select page number.
17
 */
18
class PaginationFactory implements SingletonInterface, PaginatorsInterface
19
{
20
    /**
21
     * @var ContainerInterface
22
     */
23
    private $container;
24
25
    /**
26
     * @param ContainerInterface $container
27
     */
28
    public function __construct(ContainerInterface $container)
29
    {
30
        $this->container = $container;
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     *
36
     * @throws ScopeException When no request are available.
37
     */
38
    public function createPaginator(string $parameter, int $limit = 25): PaginatorInterface
39
    {
40
        if (!$this->container->has(ServerRequestInterface::class)) {
41
            throw new ScopeException("Unable to create paginator, no request scope found");
42
        }
43
44
        /**
45
         * @var array $query
46
         */
47
        $query = $this->container->get(ServerRequestInterface::class)->getQueryParams();
48
49
        //Getting page number
50
        $page = 0;
51
        if (!empty($query[$parameter]) && is_scalar($query[$parameter])) {
52
            $page = (int)$query[$parameter];
53
        }
54
55
        //Initiating paginator
56
        return $this->container->make(
57
            Paginator::class,
58
            compact('limit', 'parameter')
59
        )->withPage($page);
60
    }
61
}