Completed
Push — master ( cfbc7b...33231d )
by Jean-Christophe
01:35
created

OrmUtils   F

Complexity

Total Complexity 73

Size/Duplication

Total Lines 269
Duplicated Lines 8.55 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 73
lcom 1
cbo 6
dl 23
loc 269
rs 2.56
c 0
b 0
f 0

30 Methods

Rating   Name   Duplication   Size   Complexity  
A getModelMetadata() 0 6 2
A isSerializable() 0 3 1
A isNullable() 0 3 1
A _is() 0 7 2
A getFieldName() 0 7 3
A getFieldNames() 0 10 3
A getTableName() 0 4 2
A getJoinTables() 0 11 3
A getAllJoinTables() 7 7 2
A getKeyFieldsAndValues() 0 4 1
A getKeyFields() 0 6 2
A getMembers() 0 6 2
A getFieldTypes() 0 6 2
A getFieldType() 0 6 2
A getMembersAndValues() 4 16 5
A isNotNullOrNullAccepted() 0 4 3
A getFirstKey() 0 4 1
A getFirstKeyValue() 0 4 1
A getKeyValues() 0 4 1
B getManyToOneMembersAndValues() 0 21 7
A getMembersWithAnnotation() 0 5 2
A exists() 0 12 5
A getJoinColumnName() 0 9 2
A getAnnotationInfo() 0 5 2
A getAnnotationInfoMember() 0 15 5
A getSerializableFields() 0 5 1
A getAllFields() 0 3 1
A getFormAllFields() 12 16 5
A setFieldToMemberNames() 0 7 3
A objectAsJSON() 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 OrmUtils 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 OrmUtils, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Ubiquity\orm;
4
5
use Ubiquity\orm\parser\Reflexion;
6
use Ubiquity\cache\CacheManager;
7
use Ubiquity\utils\base\UString;
8
use Ubiquity\utils\base\UArray;
9
use Ubiquity\controllers\rest\ResponseFormatter;
10
use Ubiquity\orm\traits\OrmUtilsRelationsTrait;
11
12
/**
13
 * Object/relational mapping utilities
14
 * @author jc
15
 * @version 1.0.1
16
 */
17
class OrmUtils {
18
	
19
	use OrmUtilsRelationsTrait;
20
	
21
	private static $modelsMetadatas;
22
23
	public static function getModelMetadata($className) {
24
		if (!isset(self::$modelsMetadatas[$className])) {
25
			self::$modelsMetadatas[$className]=CacheManager::getOrmModelCache($className);
26
		}
27
		return self::$modelsMetadatas[$className];
28
	}
29
30
	public static function isSerializable($class, $member) {
31
		return !self::_is($class, $member, "#notSerializable");
32
	}
33
34
	public static function isNullable($class, $member) {
35
		return self::_is($class, $member, "#nullable");
36
	}
37
	
38
	protected static function _is($class,$member,$like){
39
		$ret=self::getAnnotationInfo($class, $like);
40
		if ($ret !== false){
41
			return \array_search($member, $ret) !== false;
42
		}
43
		return false;
44
	}
45
46
	public static function getFieldName($class, $member) {
47
		$ret=self::getAnnotationInfo($class, "#fieldNames");
48
		if ($ret === false || !isset($ret[$member])){
49
			return $member;
50
		}
51
		return $ret[$member];
52
	}
53
54
	public static function getFieldNames($model){
55
		$fields=self::getAnnotationInfo($model, "#fieldNames");
56
		$result=[];
57
		$serializables=self::getSerializableFields($model);
58
		foreach ($fields as $member=>$field){
59
			if(\array_search($member, $serializables)!==false)
60
				$result[$field]=$member;
61
		}
62
		return $result;
63
	}
64
65
	public static function getTableName($class) {
66
		if(isset(self::getModelMetadata($class)["#tableName"]))
67
		return self::getModelMetadata($class)["#tableName"];
68
	}
69
	
70
	public static function getJoinTables($class){
71
		$result=[];
72
		
73
		if(isset(self::getModelMetadata($class)["#joinTable"])){
74
			$jts=self::getModelMetadata($class)["#joinTable"];
75
			foreach ($jts as $jt){
76
				$result[]=$jt["name"];
77
			}
78
		}
79
		return $result;
80
	}
81
	
82 View Code Duplication
	public static function getAllJoinTables($models){
83
		$result=[];
84
		foreach ($models as $model){
85
			$result=array_merge($result,self::getJoinTables($model));
86
		}
87
		return $result;
88
	}
89
90
	public static function getKeyFieldsAndValues($instance) {
91
		$kf=self::getAnnotationInfo(get_class($instance), "#primaryKeys");
92
		return self::getMembersAndValues($instance, $kf);
93
	}
94
95
	public static function getKeyFields($instance) {
96
		if(!\is_string($instance)){
97
			$instance=\get_class($instance);
98
		}
99
		return self::getAnnotationInfo($instance, "#primaryKeys");
100
	}
101
102
	public static function getMembers($className) {
103
		$fieldNames=self::getAnnotationInfo($className, "#fieldNames");
104
		if ($fieldNames !== false)
105
			return \array_keys($fieldNames);
106
		return [ ];
107
	}
108
109
	public static function getFieldTypes($className) {
110
		$fieldTypes=self::getAnnotationInfo($className, "#fieldTypes");
111
		if ($fieldTypes !== false)
112
			return $fieldTypes;
113
		return [ ];
114
	}
115
116
	public static function getFieldType($className,$field){
117
		$types= self::getFieldTypes($className);
118
		if(isset($types[$field]))
119
			return $types[$field];
120
		return "int";
121
	}
122
123
	public static function getMembersAndValues($instance, $members=NULL) {
124
		$ret=array ();
125
		$className=get_class($instance);
126
		if (is_null($members))
127
			$members=self::getMembers($className);
128
		foreach ( $members as $member ) {
129
			if (OrmUtils::isSerializable($className, $member)) {
130
				$v=Reflexion::getMemberValue($instance, $member);
131 View Code Duplication
				if (self::isNotNullOrNullAccepted($v, $className, $member)) {
132
					$name=self::getFieldName($className, $member);
133
					$ret[$name]=$v;
134
				}
135
			}
136
		}
137
		return $ret;
138
	}
139
140
	public static function isNotNullOrNullAccepted($v, $className, $member) {
141
		$notNull=UString::isNotNull($v);
142
		return ($notNull) || (!$notNull && OrmUtils::isNullable($className, $member));
143
	}
144
145
	public static function getFirstKey($class) {
146
		$kf=self::getAnnotationInfo($class, "#primaryKeys");
147
		return \reset($kf);
148
	}
149
150
	public static function getFirstKeyValue($instance) {
151
		$fkv=self::getKeyFieldsAndValues($instance);
152
		return \reset($fkv);
153
	}
154
	
155
	public static function getKeyValues($instance) {
156
		$fkv=self::getKeyFieldsAndValues($instance);
157
		return implode("_",$fkv);
158
	}
159
160
	/**
161
	 *
162
	 * @param object $instance
163
	 * @return mixed[]
164
	 */
165
	public static function getManyToOneMembersAndValues($instance) {
166
		$ret=array ();
167
		$class=get_class($instance);
168
		$members=self::getAnnotationInfo($class, "#manyToOne");
169
		if ($members !== false) {
170
			foreach ( $members as $member ) {
171
				$memberAccessor="get" . ucfirst($member);
172
				if (method_exists($instance, $memberAccessor)) {
173
					$memberInstance=$instance->$memberAccessor();
174
					if (isset($memberInstance) && is_object($memberInstance)) {
175
						$keyValues=self::getKeyFieldsAndValues($memberInstance);
176
						if (sizeof($keyValues) > 0) {
177
							$fkName=self::getJoinColumnName($class, $member);
178
							$ret[$fkName]=reset($keyValues);
179
						}
180
					}
181
				}
182
			}
183
		}
184
		return $ret;
185
	}
186
187
	public static function getMembersWithAnnotation($class, $annotation) {
188
		if (isset(self::getModelMetadata($class)[$annotation]))
189
			return self::getModelMetadata($class)[$annotation];
190
		return [ ];
191
	}
192
193
	/**
194
	 *
195
	 * @param object $instance
196
	 * @param string $memberKey
197
	 * @param array $array
198
	 * @return boolean
199
	 */
200
	public static function exists($instance, $memberKey, $array) {
201
		$accessor="get" . ucfirst($memberKey);
202
		if (method_exists($instance, $accessor)) {
203
			if ($array !== null) {
204
				foreach ( $array as $value ) {
205
					if ($value->$accessor() == $instance->$accessor())
206
						return true;
207
				}
208
			}
209
		}
210
		return false;
211
	}
212
213
	public static function getJoinColumnName($class, $member) {
214
		$annot=self::getAnnotationInfoMember($class, "#joinColumn", $member);
215
		if ($annot !== false) {
216
			$fkName=$annot["name"];
217
		} else {
218
			$fkName="id" . ucfirst(self::getTableName(ucfirst($member)));
219
		}
220
		return $fkName;
221
	}
222
223
	public static function getAnnotationInfo($class, $keyAnnotation) {
224
		if (isset(self::getModelMetadata($class)[$keyAnnotation]))
225
			return self::getModelMetadata($class)[$keyAnnotation];
226
		return false;
227
	}
228
229
	public static function getAnnotationInfoMember($class, $keyAnnotation, $member) {
230
		$info=self::getAnnotationInfo($class, $keyAnnotation);
231
		if ($info !== false) {
232
			if(UArray::isAssociative($info)){
233
				if (isset($info[$member])) {
234
					return $info[$member];
235
				}
236
			}else{
237
				if(\array_search($member, $info)!==false){
238
					return $member;
239
				}
240
			}
241
		}
242
		return false;
243
	}
244
245
	public static function getSerializableFields($class) {
246
		$notSerializable=self::getAnnotationInfo($class, "#notSerializable");
247
		$fieldNames=\array_keys(self::getAnnotationInfo($class, "#fieldNames"));
248
		return \array_diff($fieldNames, $notSerializable);
249
	}
250
	
251
	public static function getAllFields($class){
252
		return \array_keys(self::getAnnotationInfo($class, "#fieldNames"));
253
	}
254
	
255
	public static function getFormAllFields($class){
256
		$result=self::getSerializableFields($class);
257 View Code Duplication
		if ($manyToOne=self::getAnnotationInfo($class, "#manyToOne")) {
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...
258
			foreach ($manyToOne as $member){
259
				$joinColumn = OrmUtils::getAnnotationInfoMember ( $class, "#joinColumn", $member );
260
				$result[]=$joinColumn["name"];
261
			}
262
		}
263 View Code Duplication
		if ($manyToMany=self::getAnnotationInfo($class, "#manyToMany")) {
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...
264
			$manyToMany=array_keys($manyToMany);
265
			foreach ($manyToMany as $member){
266
				$result[]=$member . "Ids";
267
			}
268
		}
269
		return $result;
270
	}
271
	
272
	public static function setFieldToMemberNames(&$fields,$relFields){
273
		foreach ($fields as $index=>$field){
274
			if(isset($relFields[$field])){
275
				$fields[$index]=$relFields[$field];
276
			}
277
		}
278
	}
279
280
	public static function objectAsJSON($instance){
281
		$formatter=new ResponseFormatter();
282
		$datas=$formatter->cleanRestObject($instance);
283
		return $formatter->format(["pk"=>self::getFirstKeyValue($instance),"object"=>$datas]);
284
	}
285
}
286