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

Paginator::firstItem()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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