Completed
Push — master ( 27ae86...5d0263 )
by Jean-Christophe
02:00
created

DAORelationsTrait   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 211
Duplicated Lines 2.84 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 52
lcom 1
cbo 2
dl 6
loc 211
rs 7.9487
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A _affectsRelationObjects() 0 17 4
A affectsManyToOneFromArray() 0 7 2
B _affectsObjectsFromArray() 3 14 6
B _affectsManyToManyObjectsFromArray() 3 15 6
A getManyToManyFromArrayIds() 0 13 3
B prepareManyToMany() 0 21 5
B prepareOneToMany() 0 16 5
A prepareManyToOne() 0 9 2
B getIncludedForStep() 0 19 6
C parseEncludeMember() 0 24 7
A getInvertedJoinColumns() 0 10 3
A getToManyFields() 0 9 3

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 DAORelationsTrait 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 DAORelationsTrait, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Ubiquity\orm\traits;
4
5
use Ubiquity\orm\OrmUtils;
6
use Ubiquity\orm\parser\ManyToManyParser;
7
8
trait DAORelationsTrait {
9
	
10
	private static function _affectsRelationObjects($manyToOneQueries,$oneToManyQueries,$manyToManyParsers,$objects,$included,$useCache){
11
		if(\sizeof($manyToOneQueries)>0){
12
			self::_affectsObjectsFromArray($manyToOneQueries, $objects,$included, function($object,$member,$manyToOneObjects,$fkField){
13
				self::affectsManyToOneFromArray($object,$member,$manyToOneObjects,$fkField);
14
			});
15
		}
16
		
17
		if(\sizeof($oneToManyQueries)>0){
18
			self::_affectsObjectsFromArray($oneToManyQueries, $objects,$included, function($object,$member,$relationObjects,$fkField){
19
				self::affectsOneToManyFromArray($object,$member,$relationObjects,$fkField);
20
			});
21
		}
22
		
23
		if(\sizeof($manyToManyParsers)>0){
24
			self::_affectsManyToManyObjectsFromArray($manyToManyParsers, $objects,$included,$useCache);
25
		}
26
	}
27
	
28
	private static function affectsManyToOneFromArray($object,$member,$manyToOneObjects,$fkField){
29
		$class=\get_class($object);
30
		if(isset($object->$fkField)){
31
			$value=$manyToOneObjects[$object->$fkField];
32
			self::setToMember($member, $object, $value, $class, "getManyToOne");
33
		}
34
	}
35
	
36
	private static function _affectsObjectsFromArray($queries,$objects,$included,$affectsCallback,$useCache=NULL){
37
		$includedNext=false;
38
		foreach ($queries as $key=>$conditions){
39
			list($class,$member,$fkField)=\explode("|", $key);
40 View Code Duplication
			if(is_array($included)){
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...
41
				$includedNext=(isset($included[$member]))?(is_bool($included[$member])?$included[$member]:[$included[$member]]):false;
42
			}
43
			$condition=\implode(" OR ", $conditions);
44
			$relationObjects=self::getAll($class,$condition,$includedNext,$useCache);
45
			foreach ($objects as $object){
46
				$affectsCallback($object, $member,$relationObjects,$fkField);
47
			}
48
		}
49
	}
50
	
51
	private static function _affectsManyToManyObjectsFromArray($parsers,$objects,$included,$useCache=NULL){
52
		$includedNext=false;
53
		foreach ($parsers as $key=>$parser){
54
			list($class,$member,$inversedBy)=\explode("|", $key);
0 ignored issues
show
Unused Code introduced by
The assignment to $inversedBy is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
55 View Code Duplication
			if(is_array($included)){
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...
56
				$includedNext=(isset($included[$member]))?(is_bool($included[$member])?$included[$member]:[$included[$member]]):false;
57
			}
58
			$condition=$parser->generate();
59
			$relationObjects=self::getAll($class,$condition,$includedNext,$useCache);
60
			foreach ($objects as $object){
61
				$ret=self::getManyToManyFromArrayIds($object, $relationObjects, $member);
62
				self::setToMember($member, $object, $ret, $class, "getManyToMany");
63
			}
64
		}
65
	}
66
	
67
	
68
	
69
	private static function getManyToManyFromArrayIds($object, $relationObjects, $member){
70
		$iMember="_".$member;
71
		$ids=$object->$iMember;
72
		$ret=[];
73
		foreach ( $relationObjects as $targetEntityInstance ) {
74
			$id=OrmUtils::getFirstKeyValue($targetEntityInstance);
75
			if (array_search($id, $ids)!==false) {
76
				array_push($ret, $targetEntityInstance);
77
			}
78
		}
79
		unset($object->$iMember);
80
		return $ret;
81
	}
82
	
83
	/**
84
	 * Prepares members associated with $instance with a ManyToMany type relationship
85
	 * @param $ret array of sql conditions
86
	 * @param object $instance
87
	 * @param string $member Member on which a ManyToMany annotation must be present
88
	 * @param array $annot used internally
89
	 */
90
	private static function prepareManyToMany(&$ret,$instance, $member, $annot=null) {
91
		$class=get_class($instance);
92
		$iMember="_".$member;
93
		if (!isset($annot))
94
			$annot=OrmUtils::getAnnotationInfoMember($class, "#ManyToMany", $member);
95
			if ($annot !== false) {
96
				$key=$annot["targetEntity"]."|".$member."|".$annot["inversedBy"];
97
				if(!isset($ret[$key])){
98
					$parser=new ManyToManyParser($instance, $member);
99
					$parser->init($annot);
100
					$ret[$key]=$parser;
101
				}
102
				$accessor="get" . ucfirst($ret[$key]->getMyPk());
103
				if(method_exists($instance, $accessor)){
104
					$fkv=$instance->$accessor();
105
					$ret[$key]->addValue($fkv);
106
					$result=self::$db->fetchAll($ret[$key]->getJoinSQL($fkv));
107
					$instance->$iMember=$result;
108
				}
109
			}
110
	}
111
	
112
	/**
113
	 * Prepares members associated with $instance with a oneToMany type relationship
114
	 * @param $ret array of sql conditions
115
	 * @param object $instance
116
	 * @param string $member Member on which a OneToMany annotation must be present
117
	 * @param array $annot used internally
118
	 */
119
	private static function prepareOneToMany(&$ret,$instance, $member, $annot=null) {
120
		$class=get_class($instance);
121
		if (!isset($annot))
122
			$annot=OrmUtils::getAnnotationInfoMember($class, "#oneToMany", $member);
123
			if ($annot !== false) {
124
				$fkAnnot=OrmUtils::getAnnotationInfoMember($annot["className"], "#joinColumn", $annot["mappedBy"]);
125
				if ($fkAnnot !== false) {
126
					$fkv=OrmUtils::getFirstKeyValue($instance);
127
					$key=$annot["className"]."|".$member."|".$annot["mappedBy"];
128
					if(!isset($ret[$key])){
129
						$ret[$key]=[];
130
					}
131
					$ret[$key][$fkv]=$fkAnnot["name"] . "='" . $fkv . "'";
132
				}
133
			}
134
	}
135
	
136
	/**
137
	 * Prepares members associated with $instance with a manyToOne type relationship
138
	 * @param $ret array of sql conditions
139
	 * @param mixed $value
140
	 * @param string $fkField
141
	 * @param array $annotationArray
142
	 */
143
	private static function prepareManyToOne(&$ret, $value, $fkField,$annotationArray) {
144
		$member=$annotationArray["member"];
145
		$fk=OrmUtils::getFirstKey($annotationArray["className"]);
146
		$key=$annotationArray["className"]."|".$member."|".$fkField;
147
		if(!isset($ret[$key])){
148
			$ret[$key]=[];
149
		}
150
		$ret[$key][$value]=$fk . "='" . $value . "'";
151
	}
152
	
153
	private static function getIncludedForStep($included){
154
		if(is_bool($included)){
155
			return $included;
156
		}
157
		$ret=[];
158
		if(is_array($included)){
159
			foreach ($included as $index=>&$includedMember){
160
				if(is_array($includedMember)){
161
					foreach ($includedMember as $iMember){
162
						self::parseEncludeMember($ret, $iMember);
163
					}
164
				}else{
165
					self::parseEncludeMember($ret, $includedMember);
166
				}
167
			}
168
		}
169
		
170
		return $ret;
171
	}
172
	
173
	private static function parseEncludeMember(&$ret,$includedMember){
174
		$array=explode(".", $includedMember);
175
		$member=array_shift($array);
176
		if(sizeof($array)>0){
177
			$newValue=implode(".", $array);
178
			if($newValue==='*'){
179
				$newValue=true;
180
			}
181
			if(isset($ret[$member])){
182
				if(!is_array($ret[$member])){
183
					$ret[$member]=[$ret[$member]];
184
				}
185
				$ret[$member][]=$newValue;
186
			}else{
187
				$ret[$member]=$newValue;
188
			}
189
		}else{
190
			if(isset($member) && ""!=$member){
191
				$ret[$member]=false;
192
			}else{
193
				return;
194
			}
195
		}
196
	}
197
	
198
	private static function getInvertedJoinColumns($included,$invertedJoinColumns){
199
		$ret=[];
200
		foreach ($invertedJoinColumns as $column=>$annot){
201
			$member=$annot["member"];
202
			if(isset($included[$member])){
203
				$ret[$column]=$annot;
204
			}
205
		}
206
		return $ret;
207
	}
208
	
209
	private static function getToManyFields($included,$toManyFields){
210
		$ret=[];
211
		foreach ($toManyFields as $member=>$annot){
212
			if(isset($included[$member])){
213
				$ret[$member]=$annot;
214
			}
215
		}
216
		return $ret;
217
	}
218
}
219