Completed
Push — master ( f1914f...2e86a2 )
by dima
02:15
created

AbstractOptDataMapper::unbuildEntity()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 38
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 38
rs 6.7273
cc 7
eloc 19
nc 6
nop 1
1
<?php
2
/*
3
 * To change this license header, choose License Headers in Project Properties.
4
 * To change this template file, choose Tools | Templates
5
 * and open the template in the editor.
6
 */
7
8
namespace SimpleORM;
9
10
/**
11
 * Description of AbstractOptDataMapper
12
 *
13
 * @author d.lanec
14
 */
15
abstract class AbstractOptDataMapper extends AbstractDataMapper{
16
	
17
	protected $soft_delete_key;
18
	
19
	protected $key;
20
	
21
	protected $table;
22
	
23
	protected $mapping_fields;
24
	
25
	protected $mapping_fields_aliases;
26
	
27
	protected $relations = [];
28
29
	protected $DI;
30
			
31
	function __construct(\League\Container\Container $DI, QueryBuilderInterface $adapter, $db_name = null) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
32
		
33
		$this->DI = $DI;
34
		
35
		$this->setMappingFields();
36
		
37
		parent::__construct($adapter, $db_name);
38
	}
39
40
	/**
41
	 * Установка поля для маппинга
42
	 */
43
	protected function addMappingField($alias,$field = null){
44
		
45
		if(is_string($field)){
46
			$field = ['field'	=>	$field];
47
		}
48
		elseif(is_array($field) && !isset($field['field'])){
49
			$field['field']	= $alias;
50
		}
51
	
52
		$this->mapping_fields[$alias] = $field;
53
54
		if(isset($field['primary']) && $field['primary']===true){
55
			$this->key = $field['field'];
56
		}
57
		
58
		if(isset($field['softdelete']) && $field['softdelete']===true){
59
			$this->soft_delete_key = $field['field'];
60
		}
61
		
62
		$this->mapping_fields_aliases[$field['field']] = $alias;
63
		
64
		return $this;
65
	}
66
	
67
	/**
68
	 * Уставнока таблицы
69
	 */
70
	protected function setEntityTable() {
71
		return $this->table;
72
	}
73
74
	/**
75
	 * Установка ключа
76
	 */
77
	protected function getPrimaryKey() {
78
		return $this->key;
79
	}
80
81
	/**
82
	 * Устанвка поля для мягкого удаляения
83
	 */
84
	protected function setSoftDeleteKey() {
85
		return $this->soft_delete_key;
86
	}
87
88
	/**
89
	 * Подготавливаем конечный вариант Сущности
90
	 * 
91
	 * @param \Core\Infrastructure\EntityInterface $Entity
92
	 * @param array $row
93
	 * @return \Core\Infrastructure\EntityInterface
94
	 * @throws BadMethodCallException
95
	 */
96
	protected function buildEntity(EntityInterface $Entity, array $row){
97
		
98
        foreach ($this->mapping_fields as $alias => $cfg ) {
99
			
100
			$value = false;
101
			
102
			$field = $cfg['field'];
103
			
104
			$method_set = 'set' . ucfirst($alias);
105
			
106
			if(!method_exists($Entity, $method_set )){
107
				throw new BadMethodCallException("Метод {$method_set}  не определен");
108
			}			
109
			
110
			//событие на формирование поля
111
			if( isset($cfg['build']) && is_object($cfg['build']) ){
112
				$value = call_user_func($cfg['build'], $row);
113
			}
114
			//на связь
115
			elseif(isset($cfg['relation'])){
116
				
117
				$mapper = $this->DI->get($cfg['relation']);
118
				
119
				if($this->use_joins===true){
120
					$value = $mapper->createEntity($row);
121
				}
122
				else{
123
					$fkey = isset($cfg['on']) ? $cfg['on'] :$mapper->key;
124
					$value = $mapper->findBySpecification((new Specification)->setWhere($fkey, $row[$field]));
125
				}				
126
				
127
			}
128 View Code Duplication
			elseif(is_string($field) && isset($row[strtolower($field)])){
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
129
				$value = $row[strtolower($field)];
130
			}
131
			
132
			if($value!==false)
133
				$Entity->{$method_set}($value);
134
			
135
        }
136
		
137
        return $Entity;		
138
	}	
139
140
	
141
	/**
142
	 * из объекта формирует массив
143
	 * @param \Core\Infrastructure\EntityInterface $Entity
144
	 * @return \Core\Infrastructure\EntityInterface
145
	 * @throws BadMethodCallException
146
	 */
147
	protected function unbuildEntity(EntityInterface $Entity){
148
		
149
		$row = [];
150
151
        foreach ($this->mapping_fields as $alias => $cfg ) {
152
			
153
			$field = $cfg['field'];
154
			
155
			$method_get = 'get' . ucfirst($alias);
156
			
157
			if(!method_exists($Entity, $method_get )){
158
				throw new BadMethodCallException("Метод {$method_get}  не определен");
159
			}		
160
			
161
			//--------------------------------------------------------------------
162
			if( isset($cfg['unbuild']) && is_object($cfg['unbuild']) ){
163
				$value = call_user_func($cfg['unbuild'], $Entity->{$method_get}() );
164
			}
165
			elseif(isset($cfg['relation'])){
166
				
167
				if(isset($cfg['on']))
168
					$fkey = $this->DI->get($cfg['relation'])->getFieldAlias($cfg['on']);
169
				else
170
					$fkey = 'id';
171
				
172
				$value = $Entity->{$method_get}()->{'get'.$fkey}();
173
				
174
			}			
175
			else{
176
				$value = $Entity->{$method_get}();
177
			}			
178
						
179
			$row[$field] = $value;
180
181
        }
182
183
        return $row;		
184
	}	
185
	
186
	
187
	public function getFieldAlias($field){
188
		
189
		return $this->mapping_fields_aliases[$field];
190
		
191
	}
192
193
		/**
194
	 * Построение join-ов
195
	 */
196
	protected function setRelations(ISpecificationCriteria $Specification){
197
198
		$joins = [];
199
200
		foreach ($this->mapping_fields as $field => $cfg){
201
			if(isset($cfg['relation'])){
202
				
203
				$this->relations[$field] = $mapper = $this->DI->get($cfg['relation']);
204
205
				$table = $mapper->getEntityTable();
206
207
				$relation_key = isset($cfg['on'])? $cfg['on'] : $mapper->key;
208
				
209
				$joins[$table] = [
210
						'alias'	=> $field,
211
						//'type'	=> 'INNER',
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
212
						'on'	=> "`{$this->table}`.{$cfg['field']} = `{$field}`.{$relation_key}"
213
				];
214
215
			}
216
		}	
217
218
		if($this->use_joins===true){
219
			$Specification->setJoins($joins);
220
		}			
221
	}	
222
	
223
	/**
224
	 * На успешное сохранение
225
	 * @param \SimpleORM\EntityInterface $Entity
226
	 */
227 View Code Duplication
	protected function onSaveSuccess(EntityInterface $Entity){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
228
		
229
		
230
		foreach ($this->relations as $alias => $mapper) {
231
			$Entity = $Entity->{'get'.$alias}();
232
			if(!$mapper->save($Entity)){
233
				throw new \Autoprice\Exceptions\EntityNotSaveException('Unable to save Entity!');
234
			}
235
		}
236
		
237
		return true;
238
	}
239
	
240
	/**
241
	 * На успешное удаление
242
	 * @param \SimpleORM\EntityInterface $Entity
243
	 */
244 View Code Duplication
	protected function onDeleteSuccess(EntityInterface $Entity) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
245
		foreach ($this->relations as $alias => $mapper) {
246
			$Entity = $Entity->{'get'.$alias}();
247
			if(!$mapper->delete($Entity)){
248
				throw new \Autoprice\Exceptions\EntityNotDeleteException('Unable to delete Entity!');
249
			}
250
		}
251
		
252
		return true;
253
	}
254
}
255