Completed
Push — master ( 8e43a1...39e907 )
by Jean-Christophe
01:48
created

DAOUpdatesTrait::remove()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
dl 0
loc 5
rs 9.4285
c 2
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
namespace Ubiquity\orm\traits;
3
4
use Ubiquity\orm\OrmUtils;
5
use Ubiquity\orm\parser\Reflexion;
6
use Ubiquity\db\SqlUtils;
7
use Ubiquity\log\Logger;
8
use Ubiquity\orm\parser\ManyToManyParser;
9
10
/**
11
 * Trait for DAO Updates (Create, Update, Delete)
12
 * @author jc
13
 * @static Database $db
14
 */
15
trait DAOUpdatesTrait{
16
17
18
	/**
19
	 * Deletes the object $instance from the database
20
	 * @param object $instance instance à supprimer
21
	 */
22
	public static function remove($instance) {
23
		$tableName=OrmUtils::getTableName(get_class($instance));
24
		$keyAndValues=OrmUtils::getKeyFieldsAndValues($instance);
25
		return self::removeByKey_($tableName, $keyAndValues);
0 ignored issues
show
Documentation introduced by
$keyAndValues is of type array, but the function expects a string.

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...
26
	}
27
28
	/**
29
	 * @param string $tableName
30
	 * @param string $keyAndValues
31
	 * @return int the number of rows that were modified or deleted by the SQL statement you issued
32
	 */
33
	private static function removeByKey_($tableName,$keyAndValues){
34
		$sql="DELETE FROM " . $tableName . " WHERE " . SqlUtils::getWhere($keyAndValues);
35
		Logger::log("delete", $sql);
36
		$statement=self::$db->prepareStatement($sql);
37
		foreach ( $keyAndValues as $key => $value ) {
0 ignored issues
show
Bug introduced by
The expression $keyAndValues of type string is not traversable.
Loading history...
38
			self::$db->bindValueFromStatement($statement, $key, $value);
39
		}
40
41
		return $statement->execute();
42
	}
43
44
	/**
45
	 * @param string $tableName
46
	 * @param string $where
47
	 * @return int the number of rows that were modified or deleted by the SQL statement you issued
48
	 */
49
	private static function remove_($tableName,$where){
50
		$sql="DELETE FROM " . $tableName . " WHERE " . SqlUtils::checkWhere($where);
51
		Logger::log("delete", $sql);
52
		$statement=self::$db->prepareStatement($sql);
53
		return $statement->execute();
54
	}
55
56
	/**
57
	 * @param string $modelName
58
	 * @param array|int $ids
59
	 * @return int
60
	 */
61
	public static function delete($modelName,$ids){
62
		$tableName=OrmUtils::getTableName($modelName);
63
		$pk=OrmUtils::getFirstKey($modelName);
64
		if(!\is_array($ids)){
65
			$ids=[$ids];
66
		}
67
		$where=SqlUtils::getMultiWhere($ids, $pk);
68
		return self::remove_($tableName, $where);
69
	}
70
71
	/**
72
	 * Inserts a new instance $ instance into the database
73
	 * @param object $instance the instance to insert
74
	 * @param boolean $insertMany if true, save instances related to $instance by a ManyToMany association
75
	 */
76
	public static function insert($instance, $insertMany=false) {
77
		$tableName=OrmUtils::getTableName(get_class($instance));
78
		$keyAndValues=Reflexion::getPropertiesAndValues($instance);
79
		$keyAndValues=array_merge($keyAndValues, OrmUtils::getManyToOneMembersAndValues($instance));
80
		$sql="INSERT INTO " . $tableName . "(" . SqlUtils::getInsertFields($keyAndValues) . ") VALUES(" . SqlUtils::getInsertFieldsValues($keyAndValues) . ")";
81
		Logger::log("insert", $sql);
82
		Logger::log("Key and values", json_encode($keyAndValues));
83
		$statement=self::$db->prepareStatement($sql);
84
		foreach ( $keyAndValues as $key => $value ) {
85
			self::$db->bindValueFromStatement($statement, $key, $value);
86
		}
87
		$result=$statement->execute();
88
		if ($result) {
89
			$accesseurId="set" . ucfirst(OrmUtils::getFirstKey(get_class($instance)));
90
			$instance->$accesseurId(self::$db->lastInserId());
91
			if ($insertMany) {
92
				self::insertOrUpdateAllManyToMany($instance);
93
			}
94
		}
95
		return $result;
96
	}
97
98
	/**
99
	 * Met à jour les membres de $instance annotés par un ManyToMany
100
	 * @param object $instance
101
	 */
102
	public static function insertOrUpdateAllManyToMany($instance) {
103
		$members=OrmUtils::getAnnotationInfo(get_class($instance), "#manyToMany");
104
		if ($members !== false) {
105
			$members=\array_keys($members);
106
			foreach ( $members as $member ) {
107
				self::insertOrUpdateManyToMany($instance, $member);
108
			}
109
		}
110
	}
111
112
	/**
113
	 * Updates the $member member of $instance annotated by a ManyToMany
114
	 * @param Object $instance
115
	 * @param String $member
116
	 */
117
	public static function insertOrUpdateManyToMany($instance, $member) {
118
		$parser=new ManyToManyParser($instance, $member);
119
		if ($parser->init()) {
120
			$myField=$parser->getMyFkField();
121
			$field=$parser->getFkField();
122
			$sql="INSERT INTO `" . $parser->getJoinTable() . "`(`" . $myField . "`,`" . $field . "`) VALUES (:" . $myField . ",:" . $field . ");";
123
			$memberAccessor="get" . ucfirst($member);
124
			$memberValues=$instance->$memberAccessor();
125
			$myKey=$parser->getMyPk();
126
			$myAccessorId="get" . ucfirst($myKey);
127
			$accessorId="get" . ucfirst($parser->getPk());
128
			$id=$instance->$myAccessorId();
129
			if (!is_null($memberValues)) {
130
				self::$db->execute("DELETE FROM `" . $parser->getJoinTable() . "` WHERE `" . $myField . "`='" . $id . "'");
131
				$statement=self::$db->prepareStatement($sql);
132
				foreach ( $memberValues as $targetInstance ) {
133
					$foreignId=$targetInstance->$accessorId();
134
					$foreignInstances=self::getAll($parser->getTargetEntity(), "`" . $parser->getPk() . "`" . "='" . $foreignId . "'");
135
					if (!OrmUtils::exists($targetInstance, $parser->getPk(), $foreignInstances)) {
136
						self::insert($targetInstance, false);
137
						$foreignId=$targetInstance->$accessorId();
138
						Logger::log("InsertMany", "Insertion d'une instance de " . get_class($instance));
139
					}
140
					self::$db->bindValueFromStatement($statement, $myField, $id);
141
					self::$db->bindValueFromStatement($statement, $field, $foreignId);
142
					$statement->execute();
143
					Logger::log("InsertMany", "Insertion des valeurs dans la table association '" . $parser->getJoinTable() . "'");
144
				}
145
			}
146
		}
147
	}
148
149
	/**
150
	 * Updates an existing $instance in the database.
151
	 * Be careful not to modify the primary key
152
	 * @param object $instance instance to modify
153
	 * @param boolean $updateMany Adds or updates ManyToMany members
154
	 */
155
	public static function update($instance, $updateMany=false) {
156
		$tableName=OrmUtils::getTableName(get_class($instance));
157
		$ColumnskeyAndValues=Reflexion::getPropertiesAndValues($instance);
158
		$ColumnskeyAndValues=array_merge($ColumnskeyAndValues, OrmUtils::getManyToOneMembersAndValues($instance));
159
		$keyFieldsAndValues=OrmUtils::getKeyFieldsAndValues($instance);
160
		$sql="UPDATE " . $tableName . " SET " . SqlUtils::getUpdateFieldsKeyAndValues($ColumnskeyAndValues) . " WHERE " . SqlUtils::getWhere($keyFieldsAndValues);
161
		Logger::log("update", $sql);
162
		Logger::log("Key and values", json_encode($ColumnskeyAndValues));
163
		$statement=self::$db->prepareStatement($sql);
164
		foreach ( $ColumnskeyAndValues as $key => $value ) {
165
			self::$db->bindValueFromStatement($statement, $key, $value);
166
		}
167
		$result=$statement->execute();
168
		if ($result && $updateMany)
169
			self::insertOrUpdateAllManyToMany($instance);
170
			return $result;
171
	}
172
173
	/**
174
	 * @param object $instance
175
	 * @param boolean $updateMany
176
	 * @return int
177
	 */
178
	public static function save($instance, $updateMany=false) {
179
		if(isset($instance->_rest)){
180
			return self::update($instance,$updateMany);
181
		}
182
		return self::insert($instance,$updateMany);
183
	}
184
}
185