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

AbstractDataMapper   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 290
Duplicated Lines 1.03 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 6
Bugs 0 Features 0
Metric Value
wmc 44
c 6
b 0
f 0
lcom 1
cbo 6
dl 3
loc 290
rs 8.3396

19 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 4
A getEntityTable() 0 3 1
A getAdapter() 0 3 1
A findById() 0 6 1
B save() 0 34 5
B unbuildEntity() 0 26 4
C buildEntity() 3 29 7
setEntityTable() 0 1 ?
getPrimaryKey() 0 1 ?
setMappingFields() 0 1 ?
setSoftDeleteKey() 0 1 ?
A findBySpecification() 0 17 2
B delete() 0 20 6
A findAllBySpecification() 0 22 3
A findAll() 0 4 1
A setSoftDelete() 0 8 4
A setRelations() 0 14 3
A useJoins() 0 6 1
A withDelete() 0 5 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like AbstractDataMapper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AbstractDataMapper, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace SimpleORM;
4
5
/**
6
 * Description of AbstractDataMapper
7
 *
8
 * @author Dmitriy
9
 */
10
abstract class AbstractDataMapper implements RepositoryInterface, MapperInterface
11
{
12
	protected $db;
13
	
14
    protected $entityTable;	
15
	
16
	protected $key;
17
18
19
	/**
20
	 * Использование join при выборке
21
	 * @var type 
22
	 */
23
	protected $use_joins = false;
24
	
25
	protected $use_delete = false;
26
27
	public function __construct( QueryBuilderInterface $adapter, $db_name = null) {// \CI_DB_mysqli_driver //DatabaseAdapterInterface
28
        $this->db = $adapter;
29
		
30
		$this->entityTable = !empty($db_name)? "$db_name.".$this->setEntityTable() : $this->setEntityTable();
31
		
32
		//$this->key = $this->getKey();
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
33
	
34
		if($this->getEntityTable()=='' || $this->getPrimaryKey()==''){
35
			throw new InvalidEntityPropertyException('Свойства entityTable или key не заданы');
36
		}
37
    }
38
	
39
	
40
	
41
	function getEntityTable() {
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...
42
		return $this->entityTable;
43
	}
44
45
    public function getAdapter() {
46
        return $this->db;
47
    }
48
49
    public function findById($id)
50
    {
51
		$Criteria = (new Specification())->setWhere($this->key , $id);
52
		
53
        return $this->findBySpecification($Criteria);
54
    }	
55
	
56
	/**
57
	 * Cохранение сущности
58
	 * @param \Core\Infrastructure\EntityInterface $Entity
59
	 */
60
	public function save(EntityInterface $Entity)
61
	{
62
		
63
		$data = $this->unbuildEntity($Entity);
64
		
65
		$id = $data[$this->getPrimaryKey()];
66
		unset($data[$this->getPrimaryKey()]);
67
		
68
		//insert
69
		if (empty($id)) {
70
			
71
			unset($data[$this->setSoftDeleteKey()]);
72
			
73
			$this->db->insert($this->getEntityTable(),$data);
74
			
75
			if (!$id = $this->db->insert_id()) {
76
				return false;
77
			}
78
			
79
			$Entity->setId($id);
80
		}
81
		//update
82
		else {
83
			
84
			if(!$this->getAdapter()->update($this->getEntityTable(), $data, "{$this->getPrimaryKey()} = '{$id}'")){
85
				return false;
86
			}
87
88
		}		
89
		
90
		if(method_exists($this, 'onSaveSuccess' )){ return $this->onSaveSuccess( $Entity );}
91
		
92
		return true;
93
	}
94
	
95
	/**
96
	 * из объекта формирует массив
97
	 * @param \Core\Infrastructure\EntityInterface $Entity
98
	 * @return \Core\Infrastructure\EntityInterface
99
	 * @throws BadMethodCallException
100
	 */
101
	protected function unbuildEntity(EntityInterface $Entity){
102
		
103
		$mapfileds = array_merge([ 'id' => $this->key], $this->setMappingFields());
104
105
		$row = [];
106
		
107
        foreach ($mapfileds as $propery => $field ) {
108
			
109
			$method_get = 'get' . ucfirst($propery);
110
			
111
			if(!method_exists($Entity, $method_get )){
112
				throw new BadMethodCallException("Метод {$method_get}  не определен");
113
			}		
114
			
115
			if(method_exists($this, 'onUnBuild'.$propery )){
116
				$value = $this->{'onUnBuild'.$propery}(  $Entity->{$method_get}() );
117
			}
118
			else{
119
				$value = $Entity->{$method_get}();
120
			}			
121
			$row[$field] = $value;
122
123
        }
124
125
        return $row;		
126
	}		
127
	
128
	/**
129
	 * Подготавливаем конечный вариант Сущности
130
	 * 
131
	 * @param \Core\Infrastructure\EntityInterface $Entity
132
	 * @param array $row
133
	 * @return \Core\Infrastructure\EntityInterface
134
	 * @throws BadMethodCallException
135
	 */
136
	protected function buildEntity(EntityInterface $Entity, array $row){
137
		
138
		$mapfields = array_merge([ 'id' => $this->key], $this->setMappingFields());
139
140
        foreach ($mapfields as $propery => $field ) {
141
			
142
			$value = false;
143
			
144
			$method_set = 'set' . ucfirst($propery);
145
			
146
			if(!method_exists($Entity, $method_set )){
147
				throw new BadMethodCallException("Метод {$method_set}  не определен");
148
			}			
149
			
150
			//событие onBuildField
151
			if(method_exists($this, 'onBuild'.$propery )){
152
				$value = $this->{'onBuild'.$propery}($field,$row);
153
			}
154 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...
155
				$value = $row[strtolower($field)];
156
			}
157
			
158
			if($value!==false)
159
				$Entity->{$method_set}($value);
160
			
161
        }
162
		
163
        return $Entity;		
164
	}	
165
	
166
	
167
	abstract protected function setEntityTable();
168
	
169
	abstract protected function getPrimaryKey();
170
	
171
	abstract protected function setMappingFields();
172
	
173
	abstract protected function setSoftDeleteKey();
174
	
175
	/**
176
	 * 
177
	 * @param \Core\Infrastructure\ISpecificationCriteria $specification
178
	 * @return type
179
	 */
180
	public function findBySpecification(ISpecificationCriteria $specification){
181
182
		//псеводо удаление
183
		$this->setSoftDelete($specification);
184
		
185
		$this->setRelations($specification);
186
		
187
		$specification->setLimit(1);
188
		
189
		//получение записей
190
		$res = $this->getAdapter()->getResultQuery($this->getEntityTable(),$specification);
191
192
        if (!$row = $res->row_array()) {
193
            return null;
194
        }
195
        return $this->createEntity($row);				
196
	}
197
	
198
	/**
199
	 * Удаление записи
200
	 * @param \Core\Infrastructure\EntityInterface $Entity
201
	 * @return boolean
202
	 */
203
	public function delete(EntityInterface $Entity)
204
	{
205
		$result = false;
206
		
207
		$delete_key = $this->setSoftDeleteKey();
208
		
209
		if (
210
				$delete_key > '' && 
211
				$Entity->getId() > 0){
212
				$result = $this->db->update($this->getEntityTable(), [ $delete_key => 1 ], "{$this->getPrimaryKey()} = '{$Entity->getId()}'");
213
		}
214
		elseif($Entity->getId() > 0){
215
			
216
			if($result = $this->db->delete($this->getEntityTable(), $this->getPrimaryKey()."  = ".$Entity->getId())){
0 ignored issues
show
Documentation introduced by
$this->getPrimaryKey() .... = ' . $Entity->getId() is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
217
				if(method_exists($this, 'onDeleteSuccess' )){ $result = $this->onDeleteSuccess( $Entity );}
0 ignored issues
show
Bug introduced by
The method onDeleteSuccess() does not exist on SimpleORM\AbstractDataMapper. Did you maybe mean delete()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
218
			}
219
		}
220
		
221
		return $result;
222
	}
223
224
	public function findAllBySpecification(ISpecificationCriteria $specification)
225
	{
226
227
		$entities = [];
0 ignored issues
show
Unused Code introduced by
$entities is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
228
		
229
		//псеводо удаление
230
		$this->setSoftDelete($specification);		
231
		
232
		$this->setRelations($specification);
233
		
234
		$res = $this->getAdapter()->getResultQuery($this->getEntityTable(),$specification);
235
		
236
		if (!$rows = $res->result_array()) {
237
            return null;
238
        }	
239
		
240
		foreach($rows as $k =>  $row){
241
			$rows[$k] = $this->createEntity($row);
242
		}
243
		
244
		return $rows;		
245
	}
246
247
	public function findAll()
248
	{
249
		return $this->findAllBySpecification(new Specification());
250
	}
251
	
252
	/**
253
	 * Выборка удаленных моделей
254
	 * @param \Core\Infrastructure\ISpecificationCriteria $specification
255
	 */
256
	private function setSoftDelete(ISpecificationCriteria $specification){
257
		if(
258
				$this->use_delete === false &&
259
				$this->setSoftDeleteKey()>'' 
260
				&& !isset($specification->getWhere()[$this->setSoftDeleteKey()])
261
				)
262
		$specification->setWhere($this->setSoftDeleteKey(),0);
0 ignored issues
show
Documentation introduced by
0 is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
263
	}
264
	
265
	/**
266
	 * Построение join-ов
267
	 */
268
	protected function setRelations(ISpecificationCriteria $Specification){
269
		if($this->use_joins===true){
270
			$joins = [];
271
			
272
			foreach($this->setJoins() as $join){
0 ignored issues
show
Bug introduced by
The method setJoins() does not seem to exist on object<SimpleORM\AbstractDataMapper>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
273
				$table = (new $join['mapper']($this->getAdapter()))->setEntityTable();
274
				
275
				$joins[$table] = $join;
276
				
277
			}	
278
			
279
			$Specification->setJoins($joins);
280
		}			
281
	}
282
	
283
	/**
284
	 * Использование join-ов
285
	 */
286
	public function useJoins()
287
	{
288
		$o = clone $this;
289
		$o->use_joins = true;
0 ignored issues
show
Documentation Bug introduced by
It seems like true of type boolean is incompatible with the declared type object<SimpleORM\type> of property $use_joins.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
290
		return $o;
291
	}
292
	
293
	public function withDelete(){
294
		$o = clone $this;
295
		$o->use_delete = true;
296
		return $o;
297
	}
298
299
}
300