Completed
Push — master ( 5a683a...37dbab )
by Peter
09:05
created

MultiModelDecorator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 91.67%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 5
dl 0
loc 55
ccs 22
cts 24
cp 0.9167
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B decorate() 0 41 5
1
<?php
2
3
namespace Maslosoft\Manganel\Decorators\QueryBuilder;
4
5
use Maslosoft\Mangan\Interfaces\CriteriaAwareInterface;
6
use Maslosoft\Mangan\Interfaces\WithCriteriaInterface;
7
use Maslosoft\Manganel\Helpers\TypeNamer;
8
use Maslosoft\Manganel\Interfaces\ManganelAwareInterface;
9
use Maslosoft\Manganel\Interfaces\ModelsAwareInterface;
10
use Maslosoft\Manganel\SearchCriteria;
11
use Maslosoft\Manganel\Traits\ManganelAwareTrait;
12
use Maslosoft\Manganel\Traits\ModelsAwareTrait;
13
14
/**
15
 * MultiModelDecorator
16
 *
17
 * @author Piotr Maselkowski <pmaselkowski at gmail.com>
18
 */
19
class MultiModelDecorator implements ManganelAwareInterface,
20
		ModelsAwareInterface
21
{
22
23
	use ManganelAwareTrait,
24
	  ModelsAwareTrait;
25
26 6
	public function __construct($models)
27
	{
28 6
		$this->models = $models;
29 6
	}
30
31 6
	public function decorate(&$body, SearchCriteria $initialCriteria)
32
	{
33 6
		$queries = [];
34 6
		foreach ($this->models as $model)
35
		{
36 6
			$modelCriteria = null;
37 6
			if ($model instanceof CriteriaAwareInterface)
38
			{
39
				$modelCriteria = $model->getCriteria();
40
			}
41
			elseif ($model instanceof WithCriteriaInterface)
42
			{
43 2
				$modelCriteria = $model->getDbCriteria(false);
44
			}
45 6
			if (empty($modelCriteria))
46
			{
47 4
				$criteria = $initialCriteria;
48
			}
49
			else
50
			{
51 2
				$criteria = clone $initialCriteria;
52 2
				$criteria->mergeWith($modelCriteria);
53
			}
54 6
			$partial = [];
55 6
			(new SingleModelDecorator($model))
56 6
					->setManganel($this->manganel)
57 6
					->decorate($partial, $criteria);
58
			$query = [
59
				'bool' => [
60
					'filter' => [
61
						'type' => [
62 6
							'value' => TypeNamer::nameType($model)
63
						]
64
					],
65 6
					'must' => $partial['query']
66
				]
67
			];
68 6
			$queries[] = $query;
69
		}
70 6
		$body['query']['dis_max']['queries'] = $queries;
71 6
	}
72
73
}
74