Passed
Pull Request — master (#312)
by Arman
03:34
created

ModelPaginator::fromArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 7
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
use Quantum\Model\ModelCollection;
20
use Quantum\Model\QtModel;
21
22
/**
23
 * Class ModelPaginator
24
 * @package Quantum\Paginator
25
 */
26
class ModelPaginator implements PaginatorInterface
27
{
28
29
    use PaginatorTrait;
30
31
    /**
32
     * @var string
33
     */
34
    private $modelClass;
35
36
    /**
37
     * @var QtModel
38
     */
39
    private $model;
40
41
    /**
42
     * @param QtModel $model
43
     * @param int $perPage
44
     * @param int $page
45
     */
46
    public function __construct(QtModel $model, int $perPage, int $page = 1)
47
    {
48
        $this->initialize($perPage, $page);
49
50
        $this->model = $model;
51
        $this->modelClass = $model->getModelName();
52
        $this->total = $model->count();
53
    }
54
55
    /**
56
     * @inheritDoc
57
     */
58
    public function data(): ModelCollection
59
    {
60
        $result = $this->model
61
            ->limit($this->perPage)
62
            ->offset($this->perPage * ($this->page - 1))
63
            ->get();
64
65
        $models = array_map(function ($item) {
66
            return wrapToModel($item->getOrmInstance(), $this->modelClass);
67
        }, iterator_to_array($result));
68
69
        return new ModelCollection($models);
70
    }
71
72
    /**
73
     * @inheritDoc
74
     */
75
    public function firstItem()
76
    {
77
        $data = $this->data();
78
79
        if ($data->isEmpty()) {
80
            return null;
81
        }
82
83
        return $data->first();
84
    }
85
86
    /**
87
     * @inheritDoc
88
     */
89
    public function lastItem()
90
    {
91
        $data = $this->data();
92
93
        if ($data->isEmpty()) {
94
            return null;
95
        }
96
97
        return $data->last();
98
    }
99
}