Completed
Push — master ( ab4a72...99f0f9 )
by Sergey
05:20
created

Paginationable::makePagination()   B

Complexity

Conditions 6
Paths 13

Size

Total Lines 42
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 7.7751

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 42
ccs 19
cts 30
cp 0.6333
rs 8.439
cc 6
eloc 27
nc 13
nop 1
crap 7.7751
1
<?php
2
3
namespace Isswp101\Persimmon\Traits;
4
5
use Exception;
6
use Isswp101\Persimmon\ElasticsearchModel;
7
use Isswp101\Persimmon\QueryBuilder\QueryBuilder;
8
9
trait Paginationable
10
{
11
    /**
12
     * @var ElasticsearchModel
13
     */
14
    public $_previous = null;
15
16
    /**
17
     * @var ElasticsearchModel
18
     */
19
    public $_next = null;
20
21
    /**
22
     * Search documents and find previous and next documents.
23
     *
24
     * @param QueryBuilder $query Query
25
     * @throws Exception
26
     */
27 2
    public function makePagination(QueryBuilder $query = null)
28
    {
29 2
        if (is_null($this->_position)) {
30
            throw new Exception('To use Paginationable trait you must fill _position property in your model');
31
        }
32
33
        /** @var ElasticsearchModel $model */
34 2
        $model = static::createInstance();
35
36 2
        $query = $query ?: new QueryBuilder();
37
38 2
        $prevDoc = null;
39 2
        $nextDoc = null;
40
41 2
        $query->fields();
42 2
        $prevPos = $this->_position - 1;
43
44 2
        if ($prevPos >= 0) {
45
            $items = $model->search($query->from($prevPos)->size(3));
46
            $prevDoc = $items->first();
47
            $items = array_values($items->toArray());
48
            if (array_key_exists(2, $items)) {
49
                $nextDoc = $items[2];
50
            }
51
        } else {
52 2
            $items = $model->search($query->from($this->_position)->size(2));
53 2
            $total = $items->getTotal();
54 2
            $nextDoc = $items->last();
55
56 2
            $last = $total - 1;
57 2
            $items = $model->search($query->from($last)->size(1));
58 2
            $prevDoc = $items->first();
59
        }
60
61 2
        if (!$nextDoc) {
62
            $items = $model->search($query->from(0)->size(1));
63
            $nextDoc = $items->first();
64
        }
65
66 2
        $this->_previous = $prevDoc;
67 2
        $this->_next = $nextDoc;
68 2
    }
69
70
    /**
71
     * Return previous document.
72
     *
73
     * @return ElasticsearchModel
74
     */
75 2
    public function getPrevious()
76
    {
77 2
        return $this->_previous;
78
    }
79
80
    /**
81
     * Return next document.
82
     *
83
     * @return ElasticsearchModel
84
     */
85 2
    public function getNext()
86
    {
87 2
        return $this->_next;
88
    }
89
}
90