1
|
|
|
<?php namespace Nord\Lumen\Elasticsearch\Pagerfanta\Adapter; |
2
|
|
|
|
3
|
|
|
use Nord\Lumen\Elasticsearch\Contracts\ElasticsearchServiceContract; |
4
|
|
|
use Nord\Lumen\Elasticsearch\Search\Search; |
5
|
|
|
use Pagerfanta\Adapter\AdapterInterface; |
6
|
|
|
|
7
|
|
|
class ElasticsearchAdapter implements AdapterInterface |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @var ElasticsearchServiceContract |
11
|
|
|
*/ |
12
|
|
|
private $elasticsearch; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var Search |
16
|
|
|
*/ |
17
|
|
|
private $search; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var array |
21
|
|
|
*/ |
22
|
|
|
private $result; |
23
|
|
|
|
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param ElasticsearchServiceContract $elasticsearch |
27
|
|
|
* @param Search $search |
28
|
|
|
*/ |
29
|
|
|
public function __construct(ElasticsearchServiceContract $elasticsearch, Search $search) |
30
|
|
|
{ |
31
|
|
|
$this->elasticsearch = $elasticsearch; |
32
|
|
|
$this->search = $search; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* @inheritdoc |
38
|
|
|
*/ |
39
|
|
|
public function getNbResults() |
40
|
|
|
{ |
41
|
|
|
$result = $this->getResult(); |
42
|
|
|
return $result['hits']['total'] ?? 0; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @inheritdoc |
48
|
|
|
*/ |
49
|
|
|
public function getSlice($offset, $length) |
50
|
|
|
{ |
51
|
|
|
$result = $this->getResult($offset, $length); |
52
|
|
|
return $result['hits']['hits'] ?? []; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param int|null $offset |
58
|
|
|
* @param int|null $length |
59
|
|
|
* @return array |
60
|
|
|
*/ |
61
|
|
|
public function getResult($offset = null, $length = null) |
62
|
|
|
{ |
63
|
|
|
if (null !== $offset && null !== $length) { |
64
|
|
|
$page = ($offset / $length) + 1; |
65
|
|
|
$size = $length; |
66
|
|
|
if ($page !== $this->search->getPage() || $size !== $this->search->getSize()) { |
67
|
|
|
$this->result = null; |
68
|
|
|
$this->search->setPage($page) |
69
|
|
|
->setSize($size); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
if (empty($this->result)) { |
74
|
|
|
$this->result = $this->elasticsearch->execute($this->search); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return $this->result; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* @return array |
83
|
|
|
*/ |
84
|
|
|
public function getAggregations() |
85
|
|
|
{ |
86
|
|
|
$result = $this->getResult(); |
87
|
|
|
return $result['aggregations'] ?? []; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|