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

QueryBuilder::count()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 2
nop 1
crap 12
1
<?php
2
3
/**
4
 * This software package is licensed under `AGPL, Commercial` license[s].
5
 *
6
 * @package maslosoft/manganel
7
 * @license AGPL, Commercial
8
 *
9
 * @copyright Copyright (c) Peter Maselkowski <[email protected]>
10
 * @link http://maslosoft.com/manganel/
11
 */
12
13
namespace Maslosoft\Manganel;
14
15
use Elasticsearch\Common\Exceptions\BadRequest400Exception;
16
use Maslosoft\Addendum\Interfaces\AnnotatedInterface;
17
use Maslosoft\Mangan\Interfaces\CriteriaAwareInterface;
18
use Maslosoft\Mangan\Interfaces\CriteriaInterface;
19
use Maslosoft\Mangan\Traits\CriteriaAwareTrait;
20
use Maslosoft\Manganel\Helpers\QueryBuilderDecorator;
21
use Maslosoft\Manganel\Helpers\RecursiveFilter;
22
use Maslosoft\Manganel\Helpers\TypeNamer;
23
use Maslosoft\Manganel\Traits\UniqueModelsAwareTrait;
24
use UnexpectedValueException;
25
26
/**
27
 * QueryBuilder
28
 * @method SearchCriteria getCriteria()
29
 * @author Piotr Maselkowski <pmaselkowski at gmail.com>
30
 */
31
class QueryBuilder implements CriteriaAwareInterface
32
{
33
34
	use CriteriaAwareTrait,
35
	  UniqueModelsAwareTrait;
36
37
	/**
38
	 * Manganel instance
39
	 * @var Manganel
40
	 */
41
	private $manganel = null;
42
43 4
	public function __construct($model = null)
44
	{
45 4
		if (!empty($model))
46
		{
47
			$this->addModel($model);
48
		}
49 4
		if (!empty($model))
50
		{
51
			$this->manganel = Manganel::create($model);
52
		}
53
		else
54
		{
55 4
			$this->manganel = Manganel::fly();
56
		}
57 4
	}
58
59
	/**
60
	 * Add model or array of models
61
	 * @param AnnotatedInterface|AnnotatedInterface $model
62
	 * @return void
63
	 */
64
	public function add($model)
65
	{
66
		if (is_array($model))
67
		{
68
			foreach ($model as $m)
69
			{
70
				$this->addModel($m);
71
			}
72
			return;
73
		}
74
		$this->addModel($model);
75
	}
76
77
	/**
78
	 *
79
	 * @param string $q
80
	 * @return int
81
	 */
82
	public function count($q = null)
83
	{
84
		$params = $this->getParams($q);
85
		$result = $this->manganel->getClient()->count($params);
86
		if (empty($result) && empty($result['count']))
87
		{
88
			return 0; // @codeCoverageIgnore
89
		}
90
		return $result['count'];
91
	}
92
93
	/**
94
	 * Get search results
95
	 * @param string $q
96
	 * @return array
97
	 */
98 3
	public function search($q = null)
99
	{
100 3
		$params = $this->getParams($q);
101
102
		try
103
		{
104 3
			$result = $this->manganel->getClient()->search($params);
105
		}
106
		catch (BadRequest400Exception $e)
107
		{
108
			// Throw previous exception,
109
			// as it holds more meaningfull information
110
			$json = json_encode($params, JSON_PRETTY_PRINT);
111
			$previous = $e->getPrevious();
112
			$message = sprintf("Exception (%s) while querying `%s`: \n%s\n", $previous->getMessage(), $this->manganel->indexId, $json);
113
			throw new BadRequest400Exception($message, 400, $e);
114
		}
115
116 3
		if (empty($result) && empty($result['hits']) && empty($result['hits']['hits']))
117
		{
118
			return [];
119
		}
120 3
		return $result['hits']['hits'];
121
	}
122
123 3
	public function getParams($q = null)
124
	{
125 3
		$body = [];
126
		// Try to get query from criteria if empty
127 3
		$criteria = $this->getCriteria();
128 3
		if (!$criteria instanceof SearchCriteria && $criteria instanceof CriteriaInterface)
129
		{
130 1
			$criteria = new SearchCriteria($criteria);
131
		}
132 3
		if (empty($criteria))
133
		{
134
			$criteria = new SearchCriteria;
135
		}
136 3
		if (!empty($q))
137
		{
138
			$criteria->search($q);
139
		}
140
141 3
		$decorator = new QueryBuilderDecorator($this->manganel);
142 3
		$decorator->decorate($body, $criteria);
143 3
		$models = $this->getModels();
144 3
		if (empty($models))
145
		{
146
			$type = '_all';
147
		}
148
		else
149
		{
150 3
			$types = [];
151 3
			foreach ($models as $model)
152
			{
153 3
				assert($model instanceof AnnotatedInterface, new UnexpectedValueException(sprintf('Expected `%s` instance, got `%s`', AnnotatedInterface::class, is_object($model) ? get_class($model) : gettype($model))));
154 3
				$types[] = TypeNamer::nameType($model);
155
			}
156 3
			$type = implode(',', array_unique($types));
157
		}
158
159
		$params = [
160 3
			'index' => strtolower($this->manganel->index),
161 3
			'type' => $type,
162 3
			'body' => $body
163
		];
164
//		return $params;
165 3
		return RecursiveFilter::mongoIdToString($params);
166
	}
167
168
}
169