Completed
Push — master ( 84905b...948707 )
by Jean-Christophe
01:52
created

CRUDHelper::update()   C

Complexity

Conditions 16
Paths 200

Size

Total Lines 54
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 54
rs 6.0345
c 0
b 0
f 0
cc 16
eloc 37
nc 200
nop 4

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Ubiquity\controllers\crud;
4
5
use Ubiquity\orm\OrmUtils;
6
use Ubiquity\utils\http\URequest;
7
use Ubiquity\orm\DAO;
8
use Ubiquity\orm\parser\Reflexion;
9
use Ubiquity\cache\database\DbCache;
10
11
class CRUDHelper {
12
	public static function getIdentifierFunction($model) {
13
		$pks = self::getPks ( $model );
14
		return function ($index, $instance) use ($pks) {
15
			$values = [ ];
16
			foreach ( $pks as $pk ) {
17
				$getter = "get" . ucfirst ( $pk );
18
				if (method_exists ( $instance, $getter )) {
19
					$values [] = $instance->{$getter} ();
20
				}
21
			}
22
			return implode ( "_", $values );
23
		};
24
	}
25
	
26
	public static function update($instance,$values,$updateManyToOneInForm=true,$updateManyToManyInForm=false) {
27
		$className=\get_class($instance);
28
		$relations=OrmUtils::getManyToOneFields($className);
29
		$fieldTypes=OrmUtils::getFieldTypes($className);
30
		foreach ( $fieldTypes as $property => $type ) {
31
			if ($type == "tinyint(1)") {
32
				if (isset($values[$property])) {
33
					$values[$property]=1;
34
				} else {
35
					$values[$property]=0;
36
				}
37
			}
38
		}
39
		URequest::setValuesToObject($instance, $values);
40
		foreach ( $relations as $member ) {
41
			if ($updateManyToOneInForm) {
42
				$joinColumn=OrmUtils::getAnnotationInfoMember($className, "#joinColumn", $member);
43
				if ($joinColumn) {
44
					$fkClass=$joinColumn["className"];
45
					$fkField=$joinColumn["name"];
46
					if (isset($values[$fkField])) {
47
						$fkObject=DAO::getOne($fkClass, $values["$fkField"]);
48
						Reflexion::setMemberValue($instance, $member, $fkObject);
49
					}
50
				}
51
			}
52
		}
53
		if (isset($instance)) {
54
			if ($instance->_new) {
55
				$update=DAO::insert($instance);
56
			} else {
57
				$update=DAO::update($instance);
58
				if (DbCache::$active) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
59
					// TODO update dbCache
60
				}
61
			}
62
			if ($update) {
63
				if ($updateManyToManyInForm) {
64
					$relations=OrmUtils::getManyToManyFields($className);
65
					foreach ( $relations as $member ) {
66
						if (($annot=OrmUtils::getAnnotationInfoMember($className, "#manyToMany", $member)) !== false) {
67
							$newField=$member . "Ids";
68
							$fkClass=$annot["targetEntity"];
69
							$fkObjects=DAO::getAll($fkClass, self::getMultiWhere($values[$newField], $className));
70
							if (Reflexion::setMemberValue($instance, $member, $fkObjects)) {
71
								DAO::insertOrUpdateManyToMany($instance, $member);
72
							}
73
						}
74
					}
75
				}
76
			}
77
		}
78
		return $update;
0 ignored issues
show
Bug introduced by
The variable $update does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
79
	}
80
	
81
	private static function getPks($model) {
82
		$instance=new $model();
83
		return OrmUtils::getKeyFields($instance);
84
	}
85
	
86
	private static function getMultiWhere($ids, $class) {
87
		$pk=OrmUtils::getFirstKey($class);
88
		$ids=explode(",", $ids);
89
		if (sizeof($ids) < 1)
90
			return "";
91
		$strs=[ ];
92
		$idCount=\sizeof($ids);
93
		for($i=0; $i < $idCount; $i++) {
94
			$strs[]=$pk . "='" . $ids[$i] . "'";
95
		}
96
		return implode(" OR ", $strs);
97
	}
98
	
99
	public static function getFkIntance($instance,$model,$member){
100
		$result=[];
101
		if (($annot=OrmUtils::getAnnotationInfoMember($model, "#oneToMany", $member)) !== false) {
102
			$objectFK=DAO::getOneToMany($instance, $member);
103
			$fkClass=$annot["className"];
104
		} elseif (($annot=OrmUtils::getAnnotationInfoMember($model, "#manyToMany", $member)) !== false) {
105
			$objectFK=DAO::getManyToMany($instance, $member);
106
			$fkClass=$annot["targetEntity"];
107
		} else {
108
			$objectFK=Reflexion::getMemberValue($instance, $member);
109
			if (isset($objectFK))
110
				$fkClass=\get_class($objectFK);
111
		}
112
		if(isset($fkClass)){
113
			$fkTable=OrmUtils::getTableName($fkClass);
114
			$result[$member]=compact("objectFK","fkClass","fkTable");
115
		}
116
		return $result;
117
	}
118
	
119
	public static function getFKIntances($instance,$model){
120
		$result=[];
121
		$relations=OrmUtils::getFieldsInRelations($model);
122
		foreach ( $relations as $member ) {
123
			$fkInstance=self::getFkIntance($instance, $model, $member);
124
			if(sizeof($fkInstance)>0){
125
				$result=array_merge($result,$fkInstance);
126
			}
127
		}
128
		return $result;
129
	}
130
}
131
132