1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Maslosoft\Manganel; |
4
|
|
|
|
5
|
|
|
use Maslosoft\Mangan\Abstracts\AbstractScopeManager; |
6
|
|
|
use Maslosoft\Mangan\Interfaces\ScopeManagerInterface; |
7
|
|
|
use Maslosoft\Manganel\Interfaces\ModelsAwareInterface; |
8
|
|
|
use Maslosoft\Manganel\Traits\UniqueModelsAwareTrait; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Scope Manager with support for many models |
12
|
|
|
* |
13
|
|
|
* TODO, maybe it's not even necessary? Will be known when SearchFinder will be |
14
|
|
|
* implemented... |
15
|
|
|
* |
16
|
|
|
* @author Piotr Maselkowski <pmaselkowski at gmail.com> |
17
|
|
|
*/ |
18
|
|
|
class MultiScopeManager extends AbstractScopeManager implements ScopeManagerInterface, |
19
|
|
|
ModelsAwareInterface |
20
|
|
|
{ |
21
|
|
|
|
22
|
|
|
use UniqueModelsAwareTrait; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* |
26
|
|
|
* @param object $model Base model used for criteria |
27
|
|
|
* @param object[] $models Additional models used for criteria |
28
|
|
|
*/ |
29
|
4 |
|
public function __construct($model, $models = []) |
30
|
|
|
{ |
31
|
4 |
|
$this->setModel($model); |
32
|
4 |
|
$this->setModels($models); |
33
|
4 |
|
} |
34
|
|
|
|
35
|
|
|
public function getNewCriteria($criteria = null) |
36
|
|
|
{ |
37
|
|
|
$newCriteria = new SearchCriteria($criteria); |
38
|
|
|
$newCriteria->decorateWith($this->getModel()); |
39
|
|
|
return $newCriteria; |
40
|
|
|
} |
41
|
|
|
|
42
|
3 |
|
protected function getModelCriteria() |
43
|
|
|
{ |
44
|
3 |
|
$criteria = new SearchCriteria; |
45
|
|
|
|
46
|
3 |
|
foreach ($this->getModels() as $model) |
47
|
|
|
{ |
48
|
3 |
|
$criteria->mergeWith($this->getOneModelCriteria($model)); |
|
|
|
|
49
|
|
|
} |
50
|
|
|
|
51
|
3 |
|
if (empty($criteria)) |
52
|
|
|
{ |
53
|
|
|
return $this->getNewCriteria(); |
54
|
|
|
} |
55
|
3 |
|
return $criteria; |
56
|
|
|
} |
57
|
|
|
|
58
|
3 |
|
private function getOneModelCriteria($model) |
59
|
|
|
{ |
60
|
3 |
|
if ($model instanceof WithCriteriaInterface) |
|
|
|
|
61
|
|
|
{ |
62
|
|
|
$criteria = $model->getDbCriteria(); |
|
|
|
|
63
|
|
|
} |
64
|
|
|
elseif ($model instanceof CriteriaAwareInterface) |
|
|
|
|
65
|
|
|
{ |
66
|
|
|
$criteria = $model->getCriteria(); |
|
|
|
|
67
|
|
|
} |
68
|
|
|
else |
69
|
|
|
{ |
70
|
3 |
|
return new SearchCriteria; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
} |
75
|
|
|
|
Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code: