1: <?php
2:
3: namespace PHPixie\ORM\Mappers\Conditions;
4:
5: class Normalizer
6: {
7: protected $conditions;
8: protected $models;
9:
10: public function __construct($conditions, $models)
11: {
12: $this->conditions = $conditions;
13: $this->models = $models;
14: }
15:
16: public function normalizeIn($inCondition)
17: {
18: $modelName = $inCondition->modelName();
19: $items = $inCondition->items();
20: $idField = $this->models->database()->config($modelName)->idField;
21:
22: $inGroup = $this->conditions->group();
23: $this->copyLogicAndNegated($inCondition, $inGroup);
24:
25: $ids = array();
26: foreach($items as $item) {
27:
28: if(is_scalar($item)) {
29: $ids[] = $item;
30: continue;
31: }
32:
33: if($item instanceof \PHPixie\ORM\Models\Type\Database\Query) {
34: $condition = $this->getSubqueryCondition($item, $idField);
35: $inGroup->add($condition);
36: continue;
37: }
38:
39: $ids[]=$item->id();
40: }
41:
42: if(!empty($ids)) {
43:
44: if(count($ids) === 1) {
45: $operator = '=';
46: $values = array(current($ids));
47: }else{
48: $operator = 'in';
49: $values = array($ids);
50: }
51:
52: $operatorCondition = $this->conditions->operator($idField, $operator, $values);
53: $this->setLogicAndNegated($operatorCondition, 'or', false);
54: $inGroup->add($operatorCondition);
55: }
56:
57: if(empty($items)) {
58: $operatorCondition = $this->conditions->operator($idField, '=', array(null));
59: $inGroup->add($operatorCondition);
60: }
61:
62: return $inGroup;
63: }
64:
65: protected function getSubqueryCondition($query, $idField)
66: {
67: if($query->getLimit() !== null || $query->getOffset() !== null) {
68: $condition = $this->conditions->subquery($idField, $query, $idField);
69:
70: }else{
71: $condition = $this->conditions->group();
72: $condition->setConditions($query->getConditions());
73: }
74:
75: $this->setLogicAndNegated($condition, 'or', false);
76: return $condition;
77: }
78:
79: protected function copyLogicAndNegated($source, $target)
80: {
81: $this->setLogicAndNegated(
82: $target,
83: $source->logic(),
84: $source->isNegated()
85: );
86: }
87:
88: protected function setLogicAndNegated($condition, $logic, $isNegated)
89: {
90: $condition->setLogic($logic);
91: $condition->setIsNegated($isNegated);
92: }
93: }