1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Maslosoft\Manganel\Adapters\Finder; |
4
|
|
|
|
5
|
|
|
use Maslosoft\Mangan\Interfaces\Adapters\FinderAdapterInterface; |
6
|
|
|
use Maslosoft\Mangan\Interfaces\CriteriaInterface; |
7
|
|
|
use Maslosoft\Mangan\Interfaces\ModelAwareInterface; |
8
|
|
|
use Maslosoft\Manganel\QueryBuilder; |
9
|
|
|
use Maslosoft\Manganel\SearchCriteria; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* ElasticSearchAdapter |
13
|
|
|
* |
14
|
|
|
* @author Piotr Maselkowski <pmaselkowski at gmail.com> |
15
|
|
|
*/ |
16
|
|
|
class ElasticSearchAdapter implements FinderAdapterInterface |
17
|
|
|
{ |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* |
21
|
|
|
* @var QueryBuilder |
22
|
|
|
*/ |
23
|
|
|
private $qb = null; |
24
|
|
|
private $models = []; |
25
|
|
|
|
26
|
30 |
|
public function __construct($models) |
27
|
|
|
{ |
28
|
30 |
|
$this->qb = new QueryBuilder(); |
29
|
30 |
|
$this->qb->setModels($models); |
30
|
30 |
|
$this->models = $models; |
31
|
30 |
|
} |
32
|
|
|
|
33
|
5 |
|
public function count(CriteriaInterface $criteria) |
34
|
|
|
{ |
35
|
5 |
|
$this->ensure($criteria); |
36
|
5 |
|
return $this->qb->setCriteria($criteria)->count(); |
37
|
|
|
} |
38
|
|
|
|
39
|
22 |
|
public function findMany(CriteriaInterface $criteria, $fields = array()) |
40
|
|
|
{ |
41
|
22 |
|
$this->prepare($criteria, $fields); |
42
|
22 |
|
return new ElasticSearchCursor($this->qb); |
43
|
|
|
} |
44
|
|
|
|
45
|
5 |
|
public function findOne(CriteriaInterface $criteria, $fields = array()) |
46
|
|
|
{ |
47
|
5 |
|
$this->prepare($criteria, $fields); |
48
|
5 |
|
$data = (new ElasticSearchCursor($this->qb))->current(); |
49
|
5 |
|
if (false === $data) |
50
|
|
|
{ |
51
|
|
|
return null; |
52
|
|
|
} |
53
|
5 |
|
return $data; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* |
58
|
|
|
* @internal Used for debugging purposes, should not be used for any manipulations! |
59
|
|
|
* @return QueryBuilder |
60
|
|
|
*/ |
61
|
1 |
|
public function getQueryBuilder() |
62
|
|
|
{ |
63
|
1 |
|
return $this->qb; |
64
|
|
|
} |
65
|
|
|
|
66
|
27 |
|
private function prepare(CriteriaInterface $criteria, $fields) |
67
|
|
|
{ |
68
|
27 |
|
$this->ensure($criteria); |
69
|
27 |
|
assert($criteria instanceof SearchCriteria); |
70
|
|
|
|
71
|
27 |
|
$this->qb->setCriteria($criteria); |
72
|
27 |
|
if (!empty($fields)) |
73
|
|
|
{ |
74
|
5 |
|
$selected = array_flip($fields); |
75
|
5 |
|
foreach ($selected as $index => $value) |
76
|
|
|
{ |
77
|
5 |
|
$selected[$index] = true; |
78
|
|
|
} |
79
|
5 |
|
$this->qb->getCriteria()->select($fields); |
80
|
|
|
} |
81
|
27 |
|
} |
82
|
|
|
|
83
|
30 |
|
private function ensure(&$criteria) |
84
|
|
|
{ |
85
|
30 |
|
if (!$criteria instanceof SearchCriteria) |
86
|
|
|
{ |
87
|
5 |
|
$criteria = new SearchCriteria($criteria); |
88
|
|
|
} |
89
|
30 |
|
$criteria->setModels($this->models); |
90
|
30 |
|
} |
91
|
|
|
|
92
|
|
|
} |
93
|
|
|
|