Completed
Push — master ( 654a3a...0d91ac )
by Arman
20s queued 16s
created

ArrayPaginator::fromArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 6
rs 10
1
<?php
2
3
/**
4
 * Quantum PHP Framework
5
 *
6
 * An open source software development framework for PHP
7
 *
8
 * @package Quantum
9
 * @author Arman Ag. <[email protected]>
10
 * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org)
11
 * @link http://quantum.softberg.org/
12
 * @since 2.9.7
13
 */
14
15
16
namespace Quantum\Paginator\Adapters;
17
18
use Quantum\Paginator\Contracts\PaginatorInterface;
19
use Quantum\Paginator\Traits\PaginatorTrait;
20
21
22
/**
23
 * Class ArrayPaginator
24
 * @package Quantum\Paginator
25
 */
26
class ArrayPaginator implements PaginatorInterface
27
{
28
29
    use PaginatorTrait;
30
31
    /**
32
     * @var array
33
     */
34
    private $items;
35
36
    /**
37
     * @param array $items
38
     * @param int $perPage
39
     * @param int $page
40
     */
41
    public function __construct(array $items, int $perPage, int $page = 1)
42
    {
43
        $this->initialize($perPage, $page);
44
        $this->items = $items;
45
        $this->total = count($items);
46
    }
47
48
    /**
49
     * @param array $params
50
     * @return PaginatorInterface
51
     */
52
    public static function fromArray(array $params): PaginatorInterface
53
    {
54
        return new self(
55
            $params['items'],
56
            $params['perPage'] ?? 10,
57
            $params['page'] ?? 1
58
        );
59
    }
60
61
    /**
62
     * @inheritDoc
63
     */
64
    public function data(): array
65
    {
66
        return array_slice(
67
            $this->items,
68
            ($this->page - 1) * $this->perPage,
69
            $this->perPage
70
        );
71
    }
72
73
    /**
74
     * @inheritDoc
75
     */
76
    public function firstItem()
77
    {
78
        $data = $this->data();
79
80
        if (empty($data)) {
81
            return null;
82
        }
83
84
        return reset($data);
85
    }
86
87
    /**
88
     * @inheritDoc
89
     */
90
    public function lastItem()
91
    {
92
        $data = $this->data();
93
94
        if (empty($data)) {
95
            return null;
96
        }
97
98
        return end($data);
99
    }
100
}