Completed
Push — multimodel-dp ( 745c1d...bcd65b )
by Peter
03:53
created

ElasticSearchAdapter::count()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
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\Manganel\QueryBuilder;
8
9
/**
10
 * ElasticSearchAdapter
11
 *
12
 * @author Piotr Maselkowski <pmaselkowski at gmail.com>
13
 */
14
class ElasticSearchAdapter implements FinderAdapterInterface
15
{
16
17
	/**
18
	 *
19
	 * @var QueryBuilder
20
	 */
21
	private $qb = null;
22
23 4
	public function __construct($models)
24
	{
25 4
		$this->qb = new QueryBuilder();
26 4
		$this->qb->setModels($models);
27 4
	}
28
29
	public function count(CriteriaInterface $criteria)
30
	{
31
		return $this->qb->setCriteria($criteria)->count();
32
	}
33
34 3
	public function findMany(CriteriaInterface $criteria, $fields = array())
35
	{
36 3
		$this->prepare($criteria, $fields);
37 3
		return new ElasticSearchCursor($this->qb);
38
	}
39
40
	public function findOne(CriteriaInterface $criteria, $fields = array())
41
	{
42
		$this->prepare($criteria, $fields);
43
		$data = (new ElasticSearchCursor(($this->qb)))->current();
44
		if (false === $data)
45
		{
46
			return null;
47
		}
48
		return $data;
49
	}
50
51
	/**
52
	 *
53
	 * @internal Used for debugging purposes, should not be used for any manipulations!
54
	 * @return QueryBuilder
55
	 */
56
	public function getQueryBuilder()
57
	{
58
		return $this->qb;
59
	}
60
61 3
	private function prepare(CriteriaInterface $criteria, $fields)
62
	{
63 3
		$this->qb->setCriteria($criteria);
64 3
		if (!empty($fields))
65
		{
66 3
			$selected = array_flip($fields);
67 3
			foreach ($selected as $index => $value)
68
			{
69 3
				$selected[$index] = true;
70
			}
71 3
			$this->qb->getCriteria()->select($fields);
72
		}
73 3
	}
74
75
}
76