Ubiquity 2.5.2
php rapid development framework
Loading...
Searching...
No Matches
DAOUpdatesTrait.php
Go to the documentation of this file.
1<?php
2
3namespace Ubiquity\orm\traits;
4
13
25
31 public static function remove($instance): ?int {
32 self::deleteAllChildren($instance);
33 $className = \get_class($instance);
34 $tableName = OrmUtils::getTableName($className);
35 $keyAndValues = OrmUtils::getKeyFieldsAndValues($instance);
36 return self::removeByKey_($className, $tableName, $keyAndValues);
37 }
38
46 private static function removeByKey_($className, $tableName, $keyAndValues): ?int {
47 $db = self::getDb($className);
48 $sql = 'DELETE FROM ' . $db->quote . $tableName . $db->quote . ' WHERE ' . SqlUtils::getWhere($keyAndValues);
49 Logger::info('DAOUpdates', $sql, 'delete');
50 $statement = $db->prepareStatement($sql);
51 try {
52 if ($statement->execute($keyAndValues)) {
53 return $statement->rowCount();
54 }
55 } catch (\PDOException $e) {
56 Logger::warn('DAOUpdates', $e->getMessage(), 'delete');
57 return null;
58 }
59 return 0;
60 }
61
71 private static function remove_($db, $tableName, $where, $params) {
72 $sql = 'DELETE FROM ' . $tableName . ' ' . SqlUtils::checkWhere($where);
73 Logger::info('DAOUpdates', $sql, 'delete');
74 $statement = $db->prepareStatement($sql);
75 try {
76 if ($statement->execute($params)) {
77 return $statement->rowCount();
78 }
79 } catch (\PDOException $e) {
80 Logger::warn('DAOUpdates', $e->getMessage(), 'delete');
81 return false;
82 }
83 }
84
93 public static function deleteAll($modelName, $where, $params = []) {
94 $db = self::getDb($modelName);
95 $quote = $db->quote;
96 $tableName = OrmUtils::getTableName($modelName);
97 return self::remove_($db, $quote . $tableName . $quote, $where, $params);
98 }
99
100 protected static function deleteManyToManyChildren(object $instance, string $memberName) {
101 $modelName = \get_class($instance);
102 $db = self::getDb($modelName);
103 $manyParser = new ManyToManyParser($db, $instance, $memberName);
104 $manyParser->init();
105 $pkv = OrmUtils::getFirstKeyValue($instance);
106 $quote = $db->quote;
107 $tableName = $manyParser->getJoinTable();
108 $fkManyField = $manyParser->getMyFkField();
109 return self::remove_($db, $quote . $tableName . $quote, "$fkManyField= ?", [$pkv]);
110 }
111
112 protected static function deleteOneToManyChildren(object $instance, string $memberName) {
113 $getter = 'get' . \ucfirst($memberName);
114 $instances = $instance->{$getter}();
115 foreach ($instances as $o) {
116 self::remove($o);
117 }
118 }
119
120
121 public static function deleteAllChildren(object $instance) {
122 $classname = \get_class($instance);
123 $oneToManyMembers = OrmUtils::getRemoveCascadeFields($classname);
124 $i = 0;
125 $count = \count($oneToManyMembers);
126 while ($i < $count) {
127 self::deleteOneToManyChildren($instance, $oneToManyMembers[$i]);
128 $i++;
129 }
130
131 $manyToManyMembers = OrmUtils::getRemoveCascadeFields($classname, '#manyToMany');
132 $j = 0;
133 $count = \count($manyToManyMembers);
134 while ($j < $count) {
135 self::deleteManyToManyChildren($instance, $manyToManyMembers[$j]);
136 $j++;
137 }
138 return $i + $j;
139 }
140
149 public static function updateAll(string $modelName, array $values, string $condition, array $params) {
150 $db = self::getDb($modelName);
151 $quote = $db->quote;
152 $tableName = OrmUtils::getTableName($modelName);
153
154 $allParams = \array_merge($values, $params);
155
156 $sql = "UPDATE {$quote}{$tableName}{$quote} SET " . SqlUtils::getUpdateFieldsKeyAndParams($values) . SqlUtils::checkWhereParams($condition, $params);
157 if (Logger::isActive()) {
158 Logger::info("DAOUpdates", $sql, "updateAll");
159 Logger::info("DAOUpdates", \json_encode($allParams), "All params");
160 }
161 $statement = $db->getUpdateStatement($sql);
162 try {
163 return $statement->execute($allParams);
164 } catch (\Exception $e) {
165 Logger::warn("DAOUpdates", $e->getMessage(), "updateAll");
166 }
167 return false;
168 }
169
177 public static function delete($modelName, $ids) {
178 $tableName = OrmUtils::getTableName($modelName);
179 $db = self::getDb($modelName);
180 $pk = OrmUtils::getFirstKey($modelName);
181 if (!\is_array($ids)) {
182 $ids = [$ids];
183 }
184 $quote = $db->quote;
185 $count = \count($ids);
186 $r = $quote . $pk . $quote . "= ?";
187 return self::remove_($db, $quote . $tableName . $quote, \str_repeat("$r OR", $count - 1) . $r, $ids);
188 }
189
190 public static function deleteById($modelName, $id) {
191 $tableName = OrmUtils::getTableName($modelName);
192 if (!\is_array($id)) {
193 $id = [OrmUtils::getFirstKey($modelName) => $id];
194 }
195 return self::removeByKey_($modelName, $tableName, $id);
196 }
197
204 public static function insert($instance, $insertMany = false) {
205 EventsManager::trigger('dao.before.insert', $instance);
206 $className = \get_class($instance);
207 $db = self::getDb($className);
208 $quote = $db->quote;
209 $tableName = OrmUtils::getTableName($className);
210 $keyAndValues = Reflexion::getPropertiesAndValues($instance);
211 $keyAndValues = \array_merge($keyAndValues, OrmUtils::getManyToOneMembersAndValues($instance));
212 $pk = OrmUtils::getFirstKey($className);
213 $pkVal = $keyAndValues [$pk] ?? null;
214 if (($pkVal) == null) {
215 unset ($keyAndValues [$pk]);
216 }
217 $sql = "INSERT INTO {$quote}{$tableName}{$quote} (" . SqlUtils::getInsertFields($keyAndValues) . ') VALUES(' . SqlUtils::getInsertFieldsValues($keyAndValues) . ')';
218 if (Logger::isActive()) {
219 Logger::info('DAOUpdates', $sql, 'insert');
220 Logger::info('DAOUpdates', \json_encode($keyAndValues), 'Key and values');
221 }
222
223 $statement = $db->getUpdateStatement($sql);
224 try {
225 $result = $statement->execute($keyAndValues);
226 if ($result) {
227 if ($pkVal == null) {
228 $lastId = $db->lastInserId("{$tableName}_{$pk}_seq");
229 if ($lastId != 0) {
230 $propKey = OrmUtils::getFirstPropKey($className);
231 $propKey->setValue($instance, $lastId);
232 $pkVal = $lastId;
233 }
234 }
235 $instance->_rest = $keyAndValues;
236 $instance->_rest [$pk] = $pkVal;
237
238 if ($insertMany) {
239 self::insertOrUpdateAllManyToMany($instance);
240 }
241 }
242 EventsManager::trigger(DAOEvents::AFTER_INSERT, $instance, $result);
243 return $result;
244 } catch (\Exception $e) {
245 Logger::warn('DAOUpdates', $e->getMessage(), 'insert');
246 if (Startup::$config ['debug']) {
247 throw $e;
248 }
249 }
250 return false;
251 }
252
258 public static function insertOrUpdateAllManyToMany($instance) {
259 $members = OrmUtils::getAnnotationInfo(get_class($instance), '#manyToMany');
260 if ($members !== false) {
261 $members = \array_keys($members);
262 foreach ($members as $member) {
263 self::insertOrUpdateManyToMany($instance, $member);
264 }
265 }
266 }
267
274 public static function insertOrUpdateManyToMany($instance, $member) {
275 $db = self::getDb(\get_class($instance));
276 $parser = new ManyToManyParser ($db, $instance, $member);
277 if ($parser->init()) {
278 $quote = $db->quote;
279 $myField = $parser->getMyFkField();
280 $field = $parser->getFkField();
281 $sql = "INSERT INTO {$quote}" . $parser->getJoinTable() . "{$quote}({$quote}" . $myField . "{$quote},{$quote}" . $field . "{$quote}) VALUES (:" . $myField . ",:" . $field . ");";
282 $memberAccessor = 'get' . \ucfirst($member);
283 $memberValues = $instance->$memberAccessor ();
284 $myKey = $parser->getMyPk();
285 $myAccessorId = 'get' . \ucfirst($myKey);
286 $accessorId = 'get' . \ucfirst($parser->getPk());
287 $id = $instance->$myAccessorId ();
288 if (!\is_null($memberValues)) {
289 $db->execute("DELETE FROM {$quote}" . $parser->getJoinTable() . "{$quote} WHERE {$quote}{$myField}{$quote}='{$id}'");
290 $statement = $db->prepareStatement($sql);
291 foreach ($memberValues as $targetInstance) {
292 $foreignId = $targetInstance->$accessorId ();
293 $foreignInstances = self::getAll($parser->getTargetEntity(), $quote . $parser->getPk() . $quote . "='{$foreignId}'");
294 if (!OrmUtils::exists($targetInstance, $parser->getPk(), $foreignInstances)) {
295 self::insert($targetInstance, false);
296 $foreignId = $targetInstance->$accessorId ();
297 Logger::info('DAOUpdates', "Insertion d'une instance de " . get_class($instance), 'InsertMany');
298 }
299 $db->bindValueFromStatement($statement, $myField, $id);
300 $db->bindValueFromStatement($statement, $field, $foreignId);
301 $statement->execute();
302 Logger::info('DAOUpdates', "Insertion des valeurs dans la table association '" . $parser->getJoinTable() . "'", 'InsertMany');
303 }
304 }
305 }
306 }
307
315 public static function update($instance, $updateMany = false) {
316 EventsManager::trigger('dao.before.update', $instance);
317 $className = \get_class($instance);
318 $db = self::getDb($className);
319 $quote = $db->quote;
320 $tableName = OrmUtils::getTableName($className);
321 $ColumnskeyAndValues = \array_merge(Reflexion::getPropertiesAndValues($instance), OrmUtils::getManyToOneMembersAndValues($instance));
322 $keyFieldsAndValues = $instance->_pkv ?? OrmUtils::getKeyFieldsAndValues($instance, '___');
323 $allParameterValues = $ColumnskeyAndValues + $keyFieldsAndValues;
324 $sql = "UPDATE {$quote}{$tableName}{$quote} SET " . SqlUtils::getUpdateFieldsKeyAndParams($ColumnskeyAndValues) . ' WHERE ' . SqlUtils::getWherePK($keyFieldsAndValues);
325 if (Logger::isActive()) {
326 Logger::info("DAOUpdates", $sql, "update");
327 Logger::info("DAOUpdates", \json_encode($allParameterValues), "Key and values");
328 }
329 $statement = $db->getUpdateStatement($sql);
330 try {
331 $result = $statement->execute($allParameterValues);
332 if ($updateMany && $result) {
333 self::insertOrUpdateAllManyToMany($instance);
334 }
335 EventsManager::trigger(DAOEvents::AFTER_UPDATE, $instance, $result);
336 $instance->_rest = \array_merge($instance->_rest, $ColumnskeyAndValues);
337 return $result;
338 } catch (\Exception $e) {
339 Logger::warn("DAOUpdates", $e->getMessage(), "update");
340 }
341 return false;
342 }
343
352 public static function updateGroup($instances, $updateMany = false) {
353 if (\count($instances) > 0) {
354 $instance = \current($instances);
355 $className = \get_class($instance);
356 $db = self::getDb($className);
357 $quote = $db->quote;
358 $tableName = OrmUtils::getTableName($className);
359 $ColumnskeyAndValues = \array_merge(Reflexion::getPropertiesAndValues($instance), OrmUtils::getManyToOneMembersAndValues($instance));
360 $keyFieldsAndValues = OrmUtils::getKeyFieldsAndValues($instance);
361 $sql = "UPDATE {$quote}{$tableName}{$quote} SET " . SqlUtils::getUpdateFieldsKeyAndParams($ColumnskeyAndValues) . ' WHERE ' . SqlUtils::getWhere($keyFieldsAndValues);
362
363 $statement = $db->getUpdateStatement($sql);
364 try {
365 $db->beginTransaction();
366 foreach ($instances as $instance) {
367 EventsManager::trigger('dao.before.update', $instance);
368 $ColumnskeyAndValues = \array_merge(Reflexion::getPropertiesAndValues($instance), OrmUtils::getManyToOneMembersAndValues($instance));
369 $result = $statement->execute($ColumnskeyAndValues);
370 if ($updateMany && $result) {
371 self::insertOrUpdateAllManyToMany($instance);
372 }
373 EventsManager::trigger(DAOEvents::AFTER_UPDATE, $instance, $result);
374 $instance->_rest = \array_merge($instance->_rest, $ColumnskeyAndValues);
375 if (Logger::isActive()) {
376 Logger::info("DAOUpdates", $sql, "update");
377 Logger::info("DAOUpdates", json_encode($ColumnskeyAndValues), "Key and values");
378 }
379 }
380 $db->commit();
381 return true;
382 } catch (\Exception $e) {
383 Logger::warn("DAOUpdates", $e->getMessage(), "update");
384 $db->rollBack();
385 }
386 }
387 return false;
388 }
389
396 public static function save($instance, $updateMany = false) {
397 if (isset ($instance->_rest)) {
398 return self::update($instance, $updateMany);
399 }
400 return self::insert($instance, $updateMany);
401 }
402}
Starts the framework.
Definition Startup.php:19
SQL utilities.
Definition SqlUtils.php:13
DAO events constants.
Definition DAOEvents.php:14
Abstract class for logging Ubiquity\log$Logger This class is part of Ubiquity.
Definition Logger.php:14
Object/relational mapping utilities.
Definition OrmUtils.php:17
static getTableName($class)
Definition OrmUtils.php:45
static getKeyFieldsAndValues($instance, $prefix='')
Definition OrmUtils.php:49
Reflection utilities in dev environment only.
Definition Reflexion.php:17
static updateGroup($instances, $updateMany=false)
Updates an array of $instances in the database.
static deleteAllChildren(object $instance)
static update($instance, $updateMany=false)
Updates an existing $instance in the database.
static updateAll(string $modelName, array $values, string $condition, array $params)
Mass update for $modelName matching the condition $where, with an associative array of $values.
static insertOrUpdateManyToMany($instance, $member)
Updates the $member member of $instance annotated by a ManyToMany.
static remove_($db, $tableName, $where, $params)
static deleteManyToManyChildren(object $instance, string $memberName)
static insertOrUpdateAllManyToMany($instance)
Updates manyToMany members.
static insert($instance, $insertMany=false)
Inserts a new instance $instance into the database.
static deleteAll($modelName, $where, $params=[])
Deletes all instances from $modelName matching the condition $where.
static deleteOneToManyChildren(object $instance, string $memberName)
static removeByKey_($className, $tableName, $keyAndValues)
static save($instance, $updateMany=false)
Ubiquity\orm\traits This class is part of Ubiquity.