Passed
Push — master ( 5305f0...4e53b3 )
by Jean-Christophe
11:14
created

DAOUpdatesTrait::updateGroup()   B

Complexity

Conditions 7
Paths 30

Size

Total Lines 35
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 3
Bugs 0 Features 1
Metric Value
eloc 29
dl 0
loc 35
ccs 0
cts 29
cp 0
rs 8.5226
c 3
b 0
f 1
cc 7
nc 30
nop 2
crap 56
1
<?php
2
3
namespace Ubiquity\orm\traits;
4
5
use Ubiquity\db\SqlUtils;
6
use Ubiquity\events\DAOEvents;
7
use Ubiquity\events\EventsManager;
8
use Ubiquity\log\Logger;
9
use Ubiquity\orm\OrmUtils;
10
use Ubiquity\orm\parser\ManyToManyParser;
11
use Ubiquity\orm\parser\Reflexion;
12
use Ubiquity\controllers\Startup;
13
14
/**
15
 * Trait for DAO Updates (Create, Update, Delete)
16
 * Ubiquity\orm\traits$DAOUpdatesTrait
17
 * This class is part of Ubiquity
18
 *
19
 * @author jcheron <[email protected]>
20
 * @version 1.1.4
21
 * @property \Ubiquity\db\Database $db
22
 *
23
 */
24
trait DAOUpdatesTrait {
25
26
	/**
27
	 * Deletes the object $instance from the database
28
	 *
29
	 * @param object $instance instance à supprimer
30
	 */
31 7
	public static function remove($instance): ?int {
32 7
		$className = \get_class ( $instance );
33 7
		$tableName = OrmUtils::getTableName ( $className );
34 7
		$keyAndValues = OrmUtils::getKeyFieldsAndValues ( $instance );
35 7
		return self::removeByKey_ ( $className, $tableName, $keyAndValues );
36
	}
37
38
	/**
39
	 *
40
	 * @param string $className
41
	 * @param string $tableName
42
	 * @param array $keyAndValues
43
	 * @return int the number of rows that were modified or deleted by the SQL statement you issued
44
	 */
45 7
	private static function removeByKey_($className, $tableName, $keyAndValues): ?int {
46 7
		$db = self::getDb ( $className );
47 7
		$sql = 'DELETE FROM ' . $db->quote . $tableName . $db->quote . ' WHERE ' . SqlUtils::getWhere ( $keyAndValues );
48 7
		Logger::info ( 'DAOUpdates', $sql, 'delete' );
49 7
		$statement = $db->prepareStatement ( $sql );
50
		try {
51 7
			if ($statement->execute ( $keyAndValues )) {
52 6
				return $statement->rowCount ();
53
			}
54 1
		} catch ( \PDOException $e ) {
55 1
			Logger::warn ( 'DAOUpdates', $e->getMessage (), 'delete' );
56 1
			return null;
57
		}
58
		return 0;
59
	}
60
61
	/**
62
	 *
63
	 * @param \Ubiquity\db\Database $db
64
	 * @param string $className
65
	 * @param string $tableName
66
	 * @param string $where
67
	 * @param array $params
68
	 * @return boolean|int the number of rows that were modified or deleted by the SQL statement you issued
69
	 */
70
	private static function remove_($db, $tableName, $where, $params) {
71
		$sql = 'DELETE FROM ' . $tableName . ' ' . SqlUtils::checkWhere ( $where );
72
		Logger::info ( 'DAOUpdates', $sql, 'delete' );
73
		$statement = $db->prepareStatement ( $sql );
74
		try {
75
			if ($statement->execute ( $params )) {
76
				return $statement->rowCount ();
77
			}
78
		} catch ( \PDOException $e ) {
79
			Logger::warn ( 'DAOUpdates', $e->getMessage (), 'delete' );
80
			return false;
81
		}
82
	}
83
84
	/**
85
	 * Deletes all instances from $modelName matching the condition $where
86
	 *
87
	 * @param string $modelName
88
	 * @param string $where
89
	 * @param array $params
90
	 * @return int|boolean
91
	 */
92
	public static function deleteAll($modelName, $where, $params = [ ]) {
93
		$db = self::getDb ( $modelName );
94
		$quote = $db->quote;
95
		$tableName = OrmUtils::getTableName ( $modelName );
96
		return self::remove_ ( $db, $quote . $tableName . $quote, $where, $params );
97
	}
98
99
	/**
100
	 * Deletes all instances from $modelName corresponding to $ids
101
	 *
102
	 * @param string $modelName
103
	 * @param array|int $ids
104
	 * @return int|boolean
105
	 */
106
	public static function delete($modelName, $ids) {
107
		$tableName = OrmUtils::getTableName ( $modelName );
108
		$db = self::getDb ( $modelName );
109
		$pk = OrmUtils::getFirstKey ( $modelName );
110
		if (! \is_array ( $ids )) {
111
			$ids = [ $ids ];
112
		}
113
		$quote = $db->quote;
114
		$count = \count ( $ids );
115
		$r = $quote . $pk . $quote . "= ?";
116
		return self::remove_ ( $db, $quote . $tableName . $quote, \str_repeat ( "$r OR", $count - 1 ) . $r, $ids );
117
	}
118
119
	/**
120
	 * Inserts a new instance $instance into the database
121
	 *
122
	 * @param object $instance the instance to insert
123
	 * @param boolean $insertMany if true, save instances related to $instance by a ManyToMany association
124
	 */
125 10
	public static function insert($instance, $insertMany = false) {
126 10
		EventsManager::trigger ( 'dao.before.insert', $instance );
127 10
		$className = \get_class ( $instance );
128 10
		$db = self::getDb ( $className );
129 10
		$quote = $db->quote;
130 10
		$tableName = OrmUtils::getTableName ( $className );
131 10
		$keyAndValues = Reflexion::getPropertiesAndValues ( $instance );
132 10
		$keyAndValues = array_merge ( $keyAndValues, OrmUtils::getManyToOneMembersAndValues ( $instance ) );
133 10
		$pk = OrmUtils::getFirstKey ( $className );
134 10
		unset ( $keyAndValues [$pk] );
135 10
		$sql = "INSERT INTO {$quote}{$tableName}{$quote} (" . SqlUtils::getInsertFields ( $keyAndValues ) . ') VALUES(' . SqlUtils::getInsertFieldsValues ( $keyAndValues ) . ')';
136 10
		if (Logger::isActive ()) {
137 10
			Logger::info ( 'DAOUpdates', $sql, 'insert' );
138 10
			Logger::info ( 'DAOUpdates', \json_encode ( $keyAndValues ), 'Key and values' );
139
		}
140
141 10
		$statement = $db->getUpdateStatement ( $sql );
142
		try {
143 10
			$result = $statement->execute ( $keyAndValues );
144 10
			if ($result) {
145 10
				$accesseurId = 'set' . \ucfirst ( $pk );
146 10
				$lastId = $db->lastInserId ( "{$tableName}_{$pk}_seq" );
147 10
				if ($lastId != 0) {
148 10
					$instance->$accesseurId ( $lastId );
149 10
					$instance->_rest = $keyAndValues;
150 10
					$instance->_rest [$pk] = $lastId;
151
				}
152 10
				if ($insertMany) {
153
					self::insertOrUpdateAllManyToMany ( $instance );
154
				}
155
			}
156 10
			EventsManager::trigger ( DAOEvents::AFTER_INSERT, $instance, $result );
157 10
			return $result;
158
		} catch ( \Exception $e ) {
159
			Logger::warn ( 'DAOUpdates', $e->getMessage (), 'insert' );
160
			if (Startup::$config ['debug']) {
161
				throw $e;
162
			}
163
		}
164
		return false;
165
	}
166
167
	/**
168
	 * Updates manyToMany members
169
	 *
170
	 * @param object $instance
171
	 */
172
	public static function insertOrUpdateAllManyToMany($instance) {
173
		$members = OrmUtils::getAnnotationInfo ( get_class ( $instance ), '#manyToMany' );
174
		if ($members !== false) {
175
			$members = \array_keys ( $members );
176
			foreach ( $members as $member ) {
177
				self::insertOrUpdateManyToMany ( $instance, $member );
178
			}
179
		}
180
	}
181
182
	/**
183
	 * Updates the $member member of $instance annotated by a ManyToMany
184
	 *
185
	 * @param Object $instance
186
	 * @param String $member
187
	 */
188
	public static function insertOrUpdateManyToMany($instance, $member) {
189
		$db = self::getDb ( \get_class ( $instance ) );
190
		$parser = new ManyToManyParser ( $db, $instance, $member );
191
		if ($parser->init ()) {
192
			$quote = $db->quote;
193
			$myField = $parser->getMyFkField ();
194
			$field = $parser->getFkField ();
195
			$sql = "INSERT INTO {$quote}" . $parser->getJoinTable () . "{$quote}({$quote}" . $myField . "{$quote},{$quote}" . $field . "{$quote}) VALUES (:" . $myField . ",:" . $field . ");";
196
			$memberAccessor = 'get' . \ucfirst ( $member );
197
			$memberValues = $instance->$memberAccessor ();
198
			$myKey = $parser->getMyPk ();
199
			$myAccessorId = 'get' . \ucfirst ( $myKey );
200
			$accessorId = 'get' . \ucfirst ( $parser->getPk () );
201
			$id = $instance->$myAccessorId ();
202
			if (! \is_null ( $memberValues )) {
203
				$db->execute ( "DELETE FROM {$quote}" . $parser->getJoinTable () . "{$quote} WHERE {$quote}{$myField}{$quote}='{$id}'" );
204
				$statement = $db->prepareStatement ( $sql );
205
				foreach ( $memberValues as $targetInstance ) {
206
					$foreignId = $targetInstance->$accessorId ();
207
					$foreignInstances = self::getAll ( $parser->getTargetEntity (), $quote . $parser->getPk () . $quote . "='{$foreignId}'" );
208
					if (! OrmUtils::exists ( $targetInstance, $parser->getPk (), $foreignInstances )) {
209
						self::insert ( $targetInstance, false );
210
						$foreignId = $targetInstance->$accessorId ();
211
						Logger::info ( 'DAOUpdates', "Insertion d'une instance de " . get_class ( $instance ), 'InsertMany' );
212
					}
213
					$db->bindValueFromStatement ( $statement, $myField, $id );
214
					$db->bindValueFromStatement ( $statement, $field, $foreignId );
215
					$statement->execute ();
216
					Logger::info ( 'DAOUpdates', "Insertion des valeurs dans la table association '" . $parser->getJoinTable () . "'", 'InsertMany' );
217
				}
218
			}
219
		}
220
	}
221
222
	/**
223
	 * Updates an existing $instance in the database.
224
	 * Be careful not to modify the primary key
225
	 *
226
	 * @param object $instance instance to modify
227
	 * @param boolean $updateMany Adds or updates ManyToMany members
228
	 */
229 2
	public static function update($instance, $updateMany = false) {
230 2
		EventsManager::trigger ( 'dao.before.update', $instance );
231 2
		$className = \get_class ( $instance );
232 2
		$db = self::getDb ( $className );
233 2
		$quote = $db->quote;
234 2
		$tableName = OrmUtils::getTableName ( $className );
235 2
		$ColumnskeyAndValues = \array_merge ( Reflexion::getPropertiesAndValues ( $instance ), OrmUtils::getManyToOneMembersAndValues ( $instance ) );
236 2
		$keyFieldsAndValues = OrmUtils::getKeyFieldsAndValues ( $instance );
237 2
		$sql = "UPDATE {$quote}{$tableName}{$quote} SET " . SqlUtils::getUpdateFieldsKeyAndParams ( $ColumnskeyAndValues ) . ' WHERE ' . SqlUtils::getWhere ( $keyFieldsAndValues );
238 2
		if (Logger::isActive ()) {
239 2
			Logger::info ( "DAOUpdates", $sql, "update" );
240 2
			Logger::info ( "DAOUpdates", json_encode ( $ColumnskeyAndValues ), "Key and values" );
241
		}
242 2
		$statement = $db->getUpdateStatement ( $sql );
243
		try {
244 2
			$result = $statement->execute ( $ColumnskeyAndValues );
245 2
			if ($updateMany && $result)
246
				self::insertOrUpdateAllManyToMany ( $instance );
247 2
			EventsManager::trigger ( DAOEvents::AFTER_UPDATE, $instance, $result );
248 2
			$instance->_rest = \array_merge ( $instance->_rest, $ColumnskeyAndValues );
249 2
			return $result;
250
		} catch ( \Exception $e ) {
251
			Logger::warn ( "DAOUpdates", $e->getMessage (), "update" );
252
		}
253
		return false;
254
	}
255
256
	/**
257
	 * Updates an array of $instances in the database.
258
	 * Be careful not to modify the primary key
259
	 *
260
	 * @param array $instances instances to modify
261
	 * @param boolean $updateMany Adds or updates ManyToMany members
262
	 * @return boolean
263
	 */
264
	public static function updateGroup($instances, $updateMany = false) {
265
		if (\count ( $instances ) > 0) {
266
			$instance = \current ( $instances );
267
			$className = \get_class ( $instance );
268
			$db = self::getDb ( $className );
269
			$quote = $db->quote;
270
			$tableName = OrmUtils::getTableName ( $className );
271
			$ColumnskeyAndValues = \array_merge ( Reflexion::getPropertiesAndValues ( $instance ), OrmUtils::getManyToOneMembersAndValues ( $instance ) );
272
			$keyFieldsAndValues = OrmUtils::getKeyFieldsAndValues ( $instance );
273
			$sql = "UPDATE {$quote}{$tableName}{$quote} SET " . SqlUtils::getUpdateFieldsKeyAndParams ( $ColumnskeyAndValues ) . ' WHERE ' . SqlUtils::getWhere ( $keyFieldsAndValues );
274
275
			$statement = $db->getUpdateStatement ( $sql );
276
			try {
277
				$db->beginTransaction ();
278
				foreach ( $instances as $instance ) {
279
					EventsManager::trigger ( 'dao.before.update', $instance );
280
					$ColumnskeyAndValues = \array_merge ( Reflexion::getPropertiesAndValues ( $instance ), OrmUtils::getManyToOneMembersAndValues ( $instance ) );
281
					$result = $statement->execute ( $ColumnskeyAndValues );
282
					if ($updateMany && $result)
283
						self::insertOrUpdateAllManyToMany ( $instance );
284
					EventsManager::trigger ( DAOEvents::AFTER_UPDATE, $instance, $result );
285
					$instance->_rest = \array_merge ( $instance->_rest, $ColumnskeyAndValues );
286
					if (Logger::isActive ()) {
287
						Logger::info ( "DAOUpdates", $sql, "update" );
288
						Logger::info ( "DAOUpdates", json_encode ( $ColumnskeyAndValues ), "Key and values" );
289
					}
290
				}
291
				$db->commit ();
292
				return true;
293
			} catch ( \Exception $e ) {
294
				Logger::warn ( "DAOUpdates", $e->getMessage (), "update" );
295
				$db->rollBack ();
296
			}
297
		}
298
		return false;
299
	}
300
301
	/**
302
	 *
303
	 * @param object $instance
304
	 * @param boolean $updateMany
305
	 * @return boolean|int
306
	 */
307
	public static function save($instance, $updateMany = false) {
308
		if (isset ( $instance->_rest )) {
309
			return self::update ( $instance, $updateMany );
310
		}
311
		return self::insert ( $instance, $updateMany );
312
	}
313
}
314