|
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
|
|
|
public function makePagination(QueryBuilder $query = null) |
|
28
|
|
|
{ |
|
29
|
|
|
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
|
|
|
$model = static::createInstance(); |
|
35
|
|
|
|
|
36
|
|
|
$query = $query ?: new QueryBuilder(); |
|
37
|
|
|
|
|
38
|
|
|
$prevDoc = null; |
|
39
|
|
|
$nextDoc = null; |
|
40
|
|
|
|
|
41
|
|
|
$query->fields(); |
|
42
|
|
|
$prevPos = $this->_position - 1; |
|
43
|
|
|
|
|
44
|
|
|
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
|
|
|
$items = $model->search($query->from($this->_position)->size(2)); |
|
53
|
|
|
$total = $items->getTotal(); |
|
54
|
|
|
$nextDoc = $items->last(); |
|
55
|
|
|
|
|
56
|
|
|
$last = $total - 1; |
|
57
|
|
|
$items = $model->search($query->from($last)->size(1)); |
|
58
|
|
|
$prevDoc = $items->first(); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
if (!$nextDoc) { |
|
62
|
|
|
$items = $model->search($query->from(0)->size(1)); |
|
63
|
|
|
$nextDoc = $items->first(); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
$this->_previous = $prevDoc; |
|
67
|
|
|
$this->_next = $nextDoc; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* Return previous document. |
|
72
|
|
|
* |
|
73
|
|
|
* @return ElasticsearchModel |
|
74
|
|
|
*/ |
|
75
|
|
|
public function getPrevious() |
|
76
|
|
|
{ |
|
77
|
|
|
return $this->_previous; |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
/** |
|
81
|
|
|
* Return next document. |
|
82
|
|
|
* |
|
83
|
|
|
* @return ElasticsearchModel |
|
84
|
|
|
*/ |
|
85
|
|
|
public function getNext() |
|
86
|
|
|
{ |
|
87
|
|
|
return $this->_next; |
|
88
|
|
|
} |
|
89
|
|
|
} |
|
90
|
|
|
|