Passed
Push — master ( ae5cc2...260dd0 )
by Jean-Christophe
08:29
created

DAOUpdatesTrait::removeByKey_()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3.0067

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 11
c 3
b 0
f 0
dl 0
loc 14
ccs 10
cts 11
cp 0.9091
rs 9.9
cc 3
nc 4
nop 3
crap 3.0067
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.5
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
		if (($keyAndValues [$pk] ?? null) == null) {
135 10
			unset ( $keyAndValues [$pk] );
136
		}
137 10
		$sql = "INSERT INTO {$quote}{$tableName}{$quote} (" . SqlUtils::getInsertFields ( $keyAndValues ) . ') VALUES(' . SqlUtils::getInsertFieldsValues ( $keyAndValues ) . ')';
138 10
		if (Logger::isActive ()) {
139 10
			Logger::info ( 'DAOUpdates', $sql, 'insert' );
140 10
			Logger::info ( 'DAOUpdates', \json_encode ( $keyAndValues ), 'Key and values' );
141
		}
142
143 10
		$statement = $db->getUpdateStatement ( $sql );
144
		try {
145 10
			$result = $statement->execute ( $keyAndValues );
146 10
			if ($result) {
147 10
				$accesseurId = 'set' . \ucfirst ( $pk );
148 10
				$lastId = $db->lastInserId ( "{$tableName}_{$pk}_seq" );
149 10
				if ($lastId != 0) {
150 10
					$instance->$accesseurId ( $lastId );
151 10
					$instance->_rest = $keyAndValues;
152 10
					$instance->_rest [$pk] = $lastId;
153
				}
154 10
				if ($insertMany) {
155
					self::insertOrUpdateAllManyToMany ( $instance );
156
				}
157
			}
158 10
			EventsManager::trigger ( DAOEvents::AFTER_INSERT, $instance, $result );
159 10
			return $result;
160
		} catch ( \Exception $e ) {
161
			Logger::warn ( 'DAOUpdates', $e->getMessage (), 'insert' );
162
			if (Startup::$config ['debug']) {
163
				throw $e;
164
			}
165
		}
166
		return false;
167
	}
168
169
	/**
170
	 * Updates manyToMany members
171
	 *
172
	 * @param object $instance
173
	 */
174
	public static function insertOrUpdateAllManyToMany($instance) {
175
		$members = OrmUtils::getAnnotationInfo ( get_class ( $instance ), '#manyToMany' );
176
		if ($members !== false) {
177
			$members = \array_keys ( $members );
178
			foreach ( $members as $member ) {
179
				self::insertOrUpdateManyToMany ( $instance, $member );
180
			}
181
		}
182
	}
183
184
	/**
185
	 * Updates the $member member of $instance annotated by a ManyToMany
186
	 *
187
	 * @param Object $instance
188
	 * @param String $member
189
	 */
190
	public static function insertOrUpdateManyToMany($instance, $member) {
191
		$db = self::getDb ( \get_class ( $instance ) );
192
		$parser = new ManyToManyParser ( $db, $instance, $member );
193
		if ($parser->init ()) {
194
			$quote = $db->quote;
195
			$myField = $parser->getMyFkField ();
196
			$field = $parser->getFkField ();
197
			$sql = "INSERT INTO {$quote}" . $parser->getJoinTable () . "{$quote}({$quote}" . $myField . "{$quote},{$quote}" . $field . "{$quote}) VALUES (:" . $myField . ",:" . $field . ");";
198
			$memberAccessor = 'get' . \ucfirst ( $member );
199
			$memberValues = $instance->$memberAccessor ();
200
			$myKey = $parser->getMyPk ();
201
			$myAccessorId = 'get' . \ucfirst ( $myKey );
202
			$accessorId = 'get' . \ucfirst ( $parser->getPk () );
203
			$id = $instance->$myAccessorId ();
204
			if (! \is_null ( $memberValues )) {
205
				$db->execute ( "DELETE FROM {$quote}" . $parser->getJoinTable () . "{$quote} WHERE {$quote}{$myField}{$quote}='{$id}'" );
206
				$statement = $db->prepareStatement ( $sql );
207
				foreach ( $memberValues as $targetInstance ) {
208
					$foreignId = $targetInstance->$accessorId ();
209
					$foreignInstances = self::getAll ( $parser->getTargetEntity (), $quote . $parser->getPk () . $quote . "='{$foreignId}'" );
210
					if (! OrmUtils::exists ( $targetInstance, $parser->getPk (), $foreignInstances )) {
211
						self::insert ( $targetInstance, false );
212
						$foreignId = $targetInstance->$accessorId ();
213
						Logger::info ( 'DAOUpdates', "Insertion d'une instance de " . get_class ( $instance ), 'InsertMany' );
214
					}
215
					$db->bindValueFromStatement ( $statement, $myField, $id );
216
					$db->bindValueFromStatement ( $statement, $field, $foreignId );
217
					$statement->execute ();
218
					Logger::info ( 'DAOUpdates', "Insertion des valeurs dans la table association '" . $parser->getJoinTable () . "'", 'InsertMany' );
219
				}
220
			}
221
		}
222
	}
223
224
	/**
225
	 * Updates an existing $instance in the database.
226
	 * Be careful not to modify the primary key
227
	 *
228
	 * @param object $instance instance to modify
229
	 * @param boolean $updateMany Adds or updates ManyToMany members
230
	 */
231 2
	public static function update($instance, $updateMany = false) {
232 2
		EventsManager::trigger ( 'dao.before.update', $instance );
233 2
		$className = \get_class ( $instance );
234 2
		$db = self::getDb ( $className );
235 2
		$quote = $db->quote;
236 2
		$tableName = OrmUtils::getTableName ( $className );
237 2
		$ColumnskeyAndValues = \array_merge ( Reflexion::getPropertiesAndValues ( $instance ), OrmUtils::getManyToOneMembersAndValues ( $instance ) );
238 2
		$keyFieldsAndValues = OrmUtils::getKeyFieldsAndValues ( $instance );
239 2
		$sql = "UPDATE {$quote}{$tableName}{$quote} SET " . SqlUtils::getUpdateFieldsKeyAndParams ( $ColumnskeyAndValues ) . ' WHERE ' . SqlUtils::getWhere ( $keyFieldsAndValues );
240 2
		if (Logger::isActive ()) {
241 2
			Logger::info ( "DAOUpdates", $sql, "update" );
242 2
			Logger::info ( "DAOUpdates", json_encode ( $ColumnskeyAndValues ), "Key and values" );
243
		}
244 2
		$statement = $db->getUpdateStatement ( $sql );
245
		try {
246 2
			$result = $statement->execute ( $ColumnskeyAndValues );
247 2
			if ($updateMany && $result) {
248
				self::insertOrUpdateAllManyToMany ( $instance );
249
			}
250 2
			EventsManager::trigger ( DAOEvents::AFTER_UPDATE, $instance, $result );
251 2
			$instance->_rest = \array_merge ( $instance->_rest, $ColumnskeyAndValues );
252 2
			return $result;
253
		} catch ( \Exception $e ) {
254
			Logger::warn ( "DAOUpdates", $e->getMessage (), "update" );
255
		}
256
		return false;
257
	}
258
259
	/**
260
	 * Updates an array of $instances in the database.
261
	 * Be careful not to modify the primary key
262
	 *
263
	 * @param array $instances instances to modify
264
	 * @param boolean $updateMany Adds or updates ManyToMany members
265
	 * @return boolean
266
	 */
267
	public static function updateGroup($instances, $updateMany = false) {
268
		if (\count ( $instances ) > 0) {
269
			$instance = \current ( $instances );
270
			$className = \get_class ( $instance );
271
			$db = self::getDb ( $className );
272
			$quote = $db->quote;
273
			$tableName = OrmUtils::getTableName ( $className );
274
			$ColumnskeyAndValues = \array_merge ( Reflexion::getPropertiesAndValues ( $instance ), OrmUtils::getManyToOneMembersAndValues ( $instance ) );
275
			$keyFieldsAndValues = OrmUtils::getKeyFieldsAndValues ( $instance );
276
			$sql = "UPDATE {$quote}{$tableName}{$quote} SET " . SqlUtils::getUpdateFieldsKeyAndParams ( $ColumnskeyAndValues ) . ' WHERE ' . SqlUtils::getWhere ( $keyFieldsAndValues );
277
278
			$statement = $db->getUpdateStatement ( $sql );
279
			try {
280
				$db->beginTransaction ();
281
				foreach ( $instances as $instance ) {
282
					EventsManager::trigger ( 'dao.before.update', $instance );
283
					$ColumnskeyAndValues = \array_merge ( Reflexion::getPropertiesAndValues ( $instance ), OrmUtils::getManyToOneMembersAndValues ( $instance ) );
284
					$result = $statement->execute ( $ColumnskeyAndValues );
285
					if ($updateMany && $result) {
286
						self::insertOrUpdateAllManyToMany ( $instance );
287
					}
288
					EventsManager::trigger ( DAOEvents::AFTER_UPDATE, $instance, $result );
289
					$instance->_rest = \array_merge ( $instance->_rest, $ColumnskeyAndValues );
290
					if (Logger::isActive ()) {
291
						Logger::info ( "DAOUpdates", $sql, "update" );
292
						Logger::info ( "DAOUpdates", json_encode ( $ColumnskeyAndValues ), "Key and values" );
293
					}
294
				}
295
				$db->commit ();
296
				return true;
297
			} catch ( \Exception $e ) {
298
				Logger::warn ( "DAOUpdates", $e->getMessage (), "update" );
299
				$db->rollBack ();
300
			}
301
		}
302
		return false;
303
	}
304
305
	/**
306
	 *
307
	 * @param object $instance
308
	 * @param boolean $updateMany
309
	 * @return boolean|int
310
	 */
311
	public static function save($instance, $updateMany = false) {
312
		if (isset ( $instance->_rest )) {
313
			return self::update ( $instance, $updateMany );
314
		}
315
		return self::insert ( $instance, $updateMany );
316
	}
317
}
318