Passed
Pull Request — master (#190)
by Arman
02:53
created

Paginator::lastItem()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
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.5
13
 */
14
15
namespace Quantum\Libraries\Database\Adapters\Sleekdb;
16
17
use Quantum\Libraries\Database\Contracts\PaginatorInterface;
18
use Quantum\Libraries\Database\Exceptions\DatabaseException;
19
use Quantum\Libraries\Database\Exceptions\ModelException;
20
use Quantum\Libraries\Database\Traits\PaginatorTrait;
21
use SleekDB\Exceptions\InvalidConfigurationException;
22
use SleekDB\Exceptions\InvalidArgumentException;
23
use SleekDB\Exceptions\IOException;
24
25
/**
26
 * Class Paginator
27
 * @package Quantum\Libraries\Database
28
 */
29
class Paginator implements PaginatorInterface
30
{
31
32
    use PaginatorTrait;
33
34
    /**
35
     * @var SleekDbal
36
     */
37
    private $dbal;
38
39
    /**
40
     * @var array
41
     */
42
    public $data;
43
44
    /**
45
     * @param $sleekDbal
46
     * @param int $perPage
47
     * @param int $page
48
     * @throws DatabaseException
49
     * @throws ModelException
50
     * @throws IOException
51
     * @throws InvalidArgumentException
52
     * @throws InvalidConfigurationException
53
     */
54
    public function __construct($sleekDbal, int $perPage, int $page = 1)
55
    {
56
        $this->total = count($sleekDbal->getBuilder()->getQuery()->fetch());
57
        $this->dbal = $sleekDbal;
58
        $this->dbal->limit($perPage)->offset($perPage * ($page - 1));
59
        $this->data = $this->dbal->getBuilder()->getQuery()->fetch();
60
        $this->perPage = $perPage;
61
        $this->page = $page;
62
        $this->baseUrl = base_url();
63
    }
64
65
    /**
66
     * @inheritDoc
67
     */
68
    public function firstItem()
69
    {
70
        return $this->data[array_key_first($this->data)];
71
    }
72
73
    /**
74
     * @inheritDoc
75
     */
76
    public function lastItem()
77
    {
78
        return $this->data[array_key_last($this->data)];
79
    }
80
81
    /**
82
     * @inheritDoc
83
     */
84
    public function data(): array
85
    {
86
        return array_map(function ($element) {
87
            $item = clone $this->dbal;
88
            $item->setData($element);
89
            $item->setModifiedFields($element);
90
            $item->setIsNew(false);
91
            return $item;
92
        }, $this->data) ?? [];
93
    }
94
}