Passed
Pull Request — master (#312)
by Arman
03:23
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.8
13
 */
14
15
namespace Quantum\Paginator\Adapters;
16
17
use Quantum\Paginator\Contracts\PaginatorInterface;
18
use Quantum\Paginator\Traits\PaginatorTrait;
19
20
21
/**
22
 * Class ArrayPaginator
23
 * @package Quantum\Paginator
24
 */
25
class ArrayPaginator implements PaginatorInterface
26
{
27
28
    use PaginatorTrait;
29
30
    /**
31
     * @var array
32
     */
33
    private $items;
34
35
    /**
36
     * @param array $items
37
     * @param int $perPage
38
     * @param int $page
39
     */
40
    public function __construct(array $items, int $perPage, int $page = 1)
41
    {
42
        $this->initialize($perPage, $page);
43
44
        $this->items = $items;
45
        $this->total = count($items);
46
    }
47
48
    /**
49
     * @inheritDoc
50
     */
51
    public function data(): array
52
    {
53
        return array_slice(
54
            $this->items,
55
            ($this->page - 1) * $this->perPage,
56
            $this->perPage
57
        );
58
    }
59
60
    /**
61
     * @inheritDoc
62
     */
63
    public function firstItem()
64
    {
65
        $data = $this->data();
66
67
        if (empty($data)) {
68
            return null;
69
        }
70
71
        return reset($data);
72
    }
73
74
    /**
75
     * @inheritDoc
76
     */
77
    public function lastItem()
78
    {
79
        $data = $this->data();
80
81
        if (empty($data)) {
82
            return null;
83
        }
84
85
        return end($data);
86
    }
87
}