Total Complexity | 78 |
Total Lines | 502 |
Duplicated Lines | 0 % |
Changes | 3 | ||
Bugs | 0 | Features | 0 |
Complex classes like BaseMapper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use BaseMapper, and based on these observations, apply Extract Interface, too.
1 | <?php declare(strict_types=1); |
||
29 | abstract class BaseMapper extends CompatibleMapper { |
||
|
|||
30 | const SQL_DATE_FORMAT = 'Y-m-d H:i:s.v'; |
||
31 | |||
32 | protected $nameColumn; |
||
33 | /** @phpstan-var class-string<EntityType> $entityClass */ |
||
34 | protected $entityClass; |
||
35 | |||
36 | /** |
||
37 | * @phpstan-param class-string<EntityType> $entityClass |
||
38 | */ |
||
39 | public function __construct(IDBConnection $db, string $tableName, string $entityClass, string $nameColumn) { |
||
40 | parent::__construct($db, $tableName, $entityClass); |
||
41 | $this->nameColumn = $nameColumn; |
||
42 | // eclipse the base class property to help phpstan |
||
43 | $this->entityClass = $entityClass; |
||
44 | } |
||
45 | |||
46 | /** |
||
47 | * Create an empty object of the entity class bound to this mapper |
||
48 | * @phpstan-return EntityType |
||
49 | */ |
||
50 | public function createEntity() : Entity { |
||
51 | return new $this->entityClass(); |
||
52 | } |
||
53 | |||
54 | /** |
||
55 | * Find a single entity by id and user_id |
||
56 | * @throws DoesNotExistException if the entity does not exist |
||
57 | * @throws MultipleObjectsReturnedException if more than one entity exists |
||
58 | * @phpstan-return EntityType |
||
59 | */ |
||
60 | public function find(int $id, string $userId) : Entity { |
||
61 | $sql = $this->selectUserEntities("`{$this->getTableName()}`.`id` = ?"); |
||
62 | return $this->findEntity($sql, [$userId, $id]); |
||
63 | } |
||
64 | |||
65 | /** |
||
66 | * Find all entities matching the given IDs. Specifying the owning user is optional. |
||
67 | * @param integer[] $ids IDs of the entities to be found |
||
68 | * @param string|null $userId |
||
69 | * @return Entity[] |
||
70 | * @phpstan-return EntityType[] |
||
71 | */ |
||
72 | public function findById(array $ids, string $userId=null) : array { |
||
84 | } |
||
85 | |||
86 | /** |
||
87 | * Find all user's entities |
||
88 | * @param string|null $createdMin Optional minimum `created` timestamp. |
||
89 | * @param string|null $createdMax Optional maximum `created` timestamp. |
||
90 | * @param string|null $updatedMin Optional minimum `updated` timestamp. |
||
91 | * @param string|null $updatedMax Optional maximum `updated` timestamp. |
||
92 | * @return Entity[] |
||
93 | * @phpstan-return EntityType[] |
||
94 | */ |
||
95 | public function findAll(string $userId, int $sortBy=SortBy::None, int $limit=null, int $offset=null, |
||
96 | ?string $createdMin=null, ?string $createdMax=null, ?string $updatedMin=null, ?string $updatedMax=null) : array { |
||
97 | $sorting = $this->formatSortingClause($sortBy); |
||
98 | [$condition, $params] = $this->formatTimestampConditions($createdMin, $createdMax, $updatedMin, $updatedMax); |
||
99 | $sql = $this->selectUserEntities($condition, $sorting); |
||
100 | \array_unshift($params, $userId); |
||
101 | return $this->findEntities($sql, $params, $limit, $offset); |
||
102 | } |
||
103 | |||
104 | /** |
||
105 | * Find all user's entities matching the given name |
||
106 | * @param string|null $createdMin Optional minimum `created` timestamp. |
||
107 | * @param string|null $createdMax Optional maximum `created` timestamp. |
||
108 | * @param string|null $updatedMin Optional minimum `updated` timestamp. |
||
109 | * @param string|null $updatedMax Optional maximum `updated` timestamp. |
||
110 | * @return Entity[] |
||
111 | * @phpstan-return EntityType[] |
||
112 | */ |
||
113 | public function findAllByName( |
||
143 | } |
||
144 | |||
145 | /** |
||
146 | * Find all user's starred entities. It is safe to call this also on entity types |
||
147 | * not supporting starring in which case an empty array will be returned. |
||
148 | * @return Entity[] |
||
149 | * @phpstan-return EntityType[] |
||
150 | */ |
||
151 | public function findAllStarred(string $userId, int $limit=null, int $offset=null) : array { |
||
159 | } |
||
160 | } |
||
161 | |||
162 | /** |
||
163 | * Find all entities matching multiple criteria, as needed for the Ampache API method `advanced_search` |
||
164 | * @param string $conjunction Operator to use between the rules, either 'and' or 'or' |
||
165 | * @param array $rules Array of arrays: [['rule' => string, 'operator' => string, 'input' => string], ...] |
||
166 | * Here, 'rule' has dozens of possible values depending on the business layer in question |
||
167 | * (see https://ampache.org/api/api-advanced-search#available-search-rules, alias names not supported here), |
||
168 | * 'operator' is one of ['contain', 'notcontain', 'start', 'end', 'is', 'isnot', '>=', '<=', '=', '!=', '>', '<', 'true', 'false'], |
||
169 | * 'input' is the right side value of the 'operator' (disregarded for the operators 'true' and 'false') |
||
170 | * @return Entity[] |
||
171 | * @phpstan-return EntityType[] |
||
172 | */ |
||
173 | public function findAllAdvanced(string $conjunction, array $rules, string $userId, ?int $limit=null, ?int $offset=null) : array { |
||
174 | $sqlConditions = []; |
||
175 | $sqlParams = [$userId]; |
||
176 | |||
177 | foreach ($rules as $rule) { |
||
178 | list('op' => $sqlOp, 'param' => $param) = $this->advFormatSqlOperator($rule['operator'], $rule['input']); |
||
179 | $sqlConditions[] = $this->advFormatSqlCondition($rule['rule'], $sqlOp); |
||
180 | if ($param !== null) { |
||
181 | $sqlParams[] = $param; |
||
182 | } |
||
183 | } |
||
184 | $sqlConditions = \implode(" $conjunction ", $sqlConditions); |
||
185 | |||
186 | $sql = $this->selectUserEntities($sqlConditions, "ORDER BY LOWER(`{$this->getTableName()}`.`{$this->nameColumn}`)"); |
||
187 | return $this->findEntities($sql, $sqlParams, $limit, $offset); |
||
188 | } |
||
189 | |||
190 | /** |
||
191 | * Find IDs of all user's entities of this kind |
||
192 | * @return int[] |
||
193 | */ |
||
194 | public function findAllIds(string $userId) : array { |
||
195 | $sql = "SELECT `id` FROM `{$this->getTableName()}` WHERE `user_id` = ?"; |
||
196 | $result = $this->execute($sql, [$userId]); |
||
197 | |||
198 | return \array_map('intval', $result->fetchAll(\PDO::FETCH_COLUMN)); |
||
199 | } |
||
200 | |||
201 | /** |
||
202 | * Find IDs of all users owning any entities of this mapper |
||
203 | * @return string[] |
||
204 | */ |
||
205 | public function findAllUsers() : array { |
||
206 | $sql = "SELECT DISTINCT(`user_id`) FROM `{$this->getTableName()}`"; |
||
207 | $result = $this->execute($sql); |
||
208 | |||
209 | return $result->fetchAll(\PDO::FETCH_COLUMN); |
||
210 | } |
||
211 | |||
212 | /** |
||
213 | * Delete all entities with given IDs without specifying the user |
||
214 | * @param integer[] $ids IDs of the entities to be deleted |
||
215 | */ |
||
216 | public function deleteById(array $ids) : void { |
||
217 | $count = \count($ids); |
||
218 | if ($count === 0) { |
||
219 | return; |
||
220 | } |
||
221 | $this->deleteByCond('`id` IN ' . $this->questionMarks($count), $ids); |
||
222 | } |
||
223 | |||
224 | /** |
||
225 | * Delete all entities matching the given SQL condition |
||
226 | * @param string $condition SQL 'WHERE' condition (without the keyword 'WHERE') |
||
227 | * @param array $params SQL parameters for the condition |
||
228 | */ |
||
229 | protected function deleteByCond(string $condition, array $params) : void { |
||
230 | $sql = "DELETE FROM `{$this->getTableName()}` WHERE ". $condition; |
||
231 | $this->execute($sql, $params); |
||
232 | } |
||
233 | |||
234 | /** |
||
235 | * Delete all entities of the given user |
||
236 | */ |
||
237 | public function deleteAll(string $userId) : void { |
||
238 | $sql = "DELETE FROM `{$this->getTableName()}` WHERE `user_id` = ?"; |
||
239 | $this->execute($sql, [$userId]); |
||
240 | } |
||
241 | |||
242 | /** |
||
243 | * Tests if entity with given ID and user ID exists in the database |
||
244 | */ |
||
245 | public function exists(int $id, string $userId) : bool { |
||
246 | $sql = "SELECT 1 FROM `{$this->getTableName()}` WHERE `id` = ? AND `user_id` = ?"; |
||
247 | $result = $this->execute($sql, [$id, $userId]); |
||
248 | return $result->rowCount() > 0; |
||
249 | } |
||
250 | |||
251 | /** |
||
252 | * Count all entities of a user |
||
253 | */ |
||
254 | public function count(string $userId) : int { |
||
255 | $sql = "SELECT COUNT(*) AS count FROM `{$this->getTableName()}` WHERE `user_id` = ?"; |
||
256 | $result = $this->execute($sql, [$userId]); |
||
257 | $row = $result->fetch(); |
||
258 | return \intval($row['count']); |
||
259 | } |
||
260 | |||
261 | /** |
||
262 | * {@inheritDoc} |
||
263 | * @see CompatibleMapper::insert() |
||
264 | * @phpstan-param EntityType $entity |
||
265 | * @phpstan-return EntityType |
||
266 | */ |
||
267 | public function insert(\OCP\AppFramework\Db\Entity $entity) : \OCP\AppFramework\Db\Entity { |
||
268 | $now = new \DateTime(); |
||
269 | $nowStr = $now->format(self::SQL_DATE_FORMAT); |
||
270 | $entity->setCreated($nowStr); |
||
271 | $entity->setUpdated($nowStr); |
||
272 | |||
273 | try { |
||
274 | return parent::insert($entity); // @phpstan-ignore-line: no way to tell phpstan that the parent uses the template type |
||
275 | } catch (\Doctrine\DBAL\Exception\UniqueConstraintViolationException $e) { |
||
276 | throw new UniqueConstraintViolationException($e->getMessage(), $e->getCode(), $e); |
||
277 | } catch (\OCP\DB\Exception $e) { |
||
278 | // Nextcloud 21+ |
||
279 | if ($e->getReason() == \OCP\DB\Exception::REASON_UNIQUE_CONSTRAINT_VIOLATION) { |
||
280 | throw new UniqueConstraintViolationException($e->getMessage(), $e->getCode(), $e); |
||
281 | } else { |
||
282 | throw $e; |
||
283 | } |
||
284 | } |
||
285 | } |
||
286 | |||
287 | /** |
||
288 | * {@inheritDoc} |
||
289 | * @see CompatibleMapper::update() |
||
290 | * @phpstan-param EntityType $entity |
||
291 | * @phpstan-return EntityType |
||
292 | */ |
||
293 | public function update(\OCP\AppFramework\Db\Entity $entity) : \OCP\AppFramework\Db\Entity { |
||
294 | $now = new \DateTime(); |
||
295 | $entity->setUpdated($now->format(self::SQL_DATE_FORMAT)); |
||
296 | return parent::update($entity); // @phpstan-ignore-line: no way to tell phpstan that the parent uses the template type |
||
297 | } |
||
298 | |||
299 | /** |
||
300 | * Insert an entity, or if an entity with the same identity already exists, |
||
301 | * update the existing entity. |
||
302 | * Note: The functions insertOrUpate and updateOrInsert get the exactly same thing done. The only difference is |
||
303 | * that the former is optimized for cases where the entity doens't exist and the latter for cases where it does exist. |
||
304 | * @return Entity The inserted or updated entity, containing also the id field |
||
305 | * @phpstan-param EntityType $entity |
||
306 | * @phpstan-return EntityType |
||
307 | */ |
||
308 | public function insertOrUpdate(Entity $entity) : Entity { |
||
309 | try { |
||
310 | return $this->insert($entity); |
||
311 | } catch (UniqueConstraintViolationException $ex) { |
||
312 | $existingEntity = $this->findUniqueEntity($entity); |
||
313 | $entity->setId($existingEntity->getId()); |
||
314 | $entity->setCreated($existingEntity->getCreated()); |
||
315 | return $this->update($entity); |
||
316 | } |
||
317 | } |
||
318 | |||
319 | /** |
||
320 | * Update an entity whose unique constraint fields match the given entity. If such entity is not found, |
||
321 | * a new entity is inserted. |
||
322 | * Note: The functions insertOrUpate and updateOrInsert get the exactly same thing done. The only difference is |
||
323 | * that the former is optimized for cases where the entity doens't exist and the latter for cases where it does exist. |
||
324 | * @return Entity The inserted or updated entity, containing also the id field |
||
325 | * @phpstan-param EntityType $entity |
||
326 | * @phpstan-return EntityType |
||
327 | */ |
||
328 | public function updateOrInsert(Entity $entity) : Entity { |
||
329 | try { |
||
330 | $existingEntity = $this->findUniqueEntity($entity); |
||
331 | $entity->setId($existingEntity->getId()); |
||
332 | return $this->update($entity); |
||
333 | } catch (DoesNotExistException $ex) { |
||
334 | try { |
||
335 | return $this->insert($entity); |
||
336 | } catch (UniqueConstraintViolationException $ex) { |
||
337 | // the conflicting entry didn't exist an eyeblink ago but now it does |
||
338 | // => this is essentially a concurrent update and it is anyway non-deterministic, which |
||
339 | // update happens last; cancel this update |
||
340 | return $this->findUniqueEntity($entity); |
||
341 | } |
||
342 | } |
||
343 | } |
||
344 | |||
345 | /** |
||
346 | * Set the "starred" column of the given entities |
||
347 | * @param \DateTime|null $date |
||
348 | * @param integer[] $ids |
||
349 | * @param string $userId |
||
350 | * @return int number of modified entities |
||
351 | */ |
||
352 | public function setStarredDate(?\DateTime $date, array $ids, string $userId) : int { |
||
353 | $count = \count($ids); |
||
354 | if (!empty($date)) { |
||
355 | $date = $date->format(self::SQL_DATE_FORMAT); |
||
356 | } |
||
357 | |||
358 | $sql = "UPDATE `{$this->getTableName()}` SET `starred` = ? |
||
359 | WHERE `id` IN {$this->questionMarks($count)} AND `user_id` = ?"; |
||
360 | $params = \array_merge([$date], $ids, [$userId]); |
||
361 | return $this->execute($sql, $params)->rowCount(); |
||
362 | } |
||
363 | |||
364 | public function latestInsertTime(string $userId) : ?\DateTime { |
||
365 | $sql = "SELECT MAX(`{$this->getTableName()}`.`created`) FROM `{$this->getTableName()}` WHERE `user_id` = ?"; |
||
366 | $result = $this->execute($sql, [$userId]); |
||
367 | $createdTime = $result->fetch(\PDO::FETCH_COLUMN); |
||
368 | |||
369 | return ($createdTime === null) ? null : new \DateTime($createdTime); |
||
370 | } |
||
371 | |||
372 | public function latestUpdateTime(string $userId) : ?\DateTime { |
||
378 | } |
||
379 | |||
380 | /** |
||
381 | * helper creating a string like '(?,?,?)' with the specified number of elements |
||
382 | */ |
||
383 | protected function questionMarks(int $count) : string { |
||
384 | $questionMarks = []; |
||
385 | for ($i = 0; $i < $count; $i++) { |
||
386 | $questionMarks[] = '?'; |
||
387 | } |
||
388 | return '(' . \implode(',', $questionMarks) . ')'; |
||
389 | } |
||
390 | |||
391 | /** |
||
392 | * Build a SQL SELECT statement which selects all entities of the given user, |
||
393 | * and optionally applies other conditions, too. |
||
394 | * This is built upon `selectEntities` which may be overridden by the derived class. |
||
395 | * @param string|null $condition Optional extra condition. This will get automatically |
||
396 | * prefixed with ' AND ', so don't include that. |
||
397 | * @param string|null $extension Any extension (e.g. ORDER BY, LIMIT) to be added after |
||
398 | * the conditions in the SQL statement |
||
399 | */ |
||
400 | protected function selectUserEntities(string $condition=null, string $extension=null) : string { |
||
401 | $allConditions = "`{$this->getTableName()}`.`user_id` = ?"; |
||
402 | |||
403 | if (!empty($condition)) { |
||
404 | $allConditions .= " AND $condition"; |
||
405 | } |
||
406 | |||
407 | return $this->selectEntities($allConditions, $extension); |
||
408 | } |
||
409 | |||
410 | /** |
||
411 | * Build a SQL SELECT statement which selects all entities matching the given condition. |
||
412 | * The derived class may override this if necessary. |
||
413 | * @param string $condition This will get automatically prefixed with ' WHERE ' |
||
414 | * @param string|null $extension Any extension (e.g. ORDER BY, LIMIT) to be added after |
||
415 | * the conditions in the SQL statement |
||
416 | */ |
||
417 | protected function selectEntities(string $condition, string $extension=null) : string { |
||
418 | return "SELECT * FROM `{$this->getTableName()}` WHERE $condition $extension "; |
||
419 | } |
||
420 | |||
421 | /** |
||
422 | * @return array with two values: The SQL condition as string and the SQL parameters as string[] |
||
423 | */ |
||
424 | protected function formatTimestampConditions(?string $createdMin, ?string $createdMax, ?string $updatedMin, ?string $updatedMax) : array { |
||
425 | $conditions = []; |
||
426 | $params = []; |
||
427 | |||
428 | if (!empty($createdMin)) { |
||
429 | $conditions[] = "`{$this->getTableName()}`.`created` >= ?"; |
||
430 | $params[] = $createdMin; |
||
431 | } |
||
432 | |||
433 | if (!empty($createdMax)) { |
||
434 | $conditions[] = "`{$this->getTableName()}`.`created` <= ?"; |
||
435 | $params[] = $createdMax; |
||
436 | } |
||
437 | |||
438 | if (!empty($updatedMin)) { |
||
439 | $conditions[] = "`{$this->getTableName()}`.`updated` >= ?"; |
||
440 | $params[] = $updatedMin; |
||
441 | } |
||
442 | |||
443 | if (!empty($updatedMax)) { |
||
444 | $conditions[] = "`{$this->getTableName()}`.`updated` <= ?"; |
||
445 | $params[] = $updatedMax; |
||
446 | } |
||
447 | |||
448 | return [\implode(' AND ', $conditions), $params]; |
||
449 | } |
||
450 | |||
451 | /** |
||
452 | * Convert given sorting condition to an SQL clause. Derived class may overide this if necessary. |
||
453 | * @param int $sortBy One of the constants defined in the class SortBy |
||
454 | */ |
||
455 | protected function formatSortingClause(int $sortBy, bool $invertSort = false) : ?string { |
||
456 | if ($sortBy == SortBy::Name) { |
||
457 | $dir = $invertSort ? 'DESC' : 'ASC'; |
||
458 | return "ORDER BY LOWER(`{$this->getTableName()}`.`{$this->nameColumn}`) $dir"; |
||
459 | } elseif ($sortBy == SortBy::Newest) { |
||
460 | $dir = $invertSort ? 'ASC' : 'DESC'; |
||
461 | return "ORDER BY `{$this->getTableName()}`.`id` $dir"; // abuse the fact that IDs are ever-incrementing values |
||
462 | } else { |
||
463 | return null; |
||
464 | } |
||
465 | } |
||
466 | |||
467 | protected static function prepareSubstringSearchPattern(string $input) : string { |
||
481 | } |
||
482 | |||
483 | /** |
||
484 | * Format SQL operator and parameter matching the given advanced search operator. |
||
485 | * @return array like ['op' => string, 'param' => string] |
||
486 | */ |
||
487 | protected function advFormatSqlOperator(string $ruleOperator, string $ruleInput) { |
||
488 | switch ($ruleOperator) { |
||
489 | case 'contain': return ['op' => 'LIKE', 'param' => "%$ruleInput%"]; |
||
490 | case 'notcontain': return ['op' => 'NOT LIKE', 'param' => "%$ruleInput%"]; |
||
491 | case 'start': return ['op' => 'LIKE', 'param' => "$ruleInput%"]; |
||
492 | case 'end': return ['op' => 'LIKE', 'param' => "%$ruleInput"]; |
||
493 | case 'is': return ['op' => '=', 'param' => "$ruleInput"]; |
||
494 | case 'isnot': return ['op' => '!=', 'param' => "$ruleInput"]; |
||
495 | case 'sounds': return ['op' => 'SOUNDS LIKE', 'param' => $ruleInput]; // MySQL-specific syntax |
||
496 | case 'notsounds': return ['op' => 'NOT SOUNDS LIKE', 'param' => $ruleInput]; // MySQL-specific syntax |
||
497 | case 'regexp': return ['op' => 'REGEXP', 'param' => $ruleInput]; // MySQL-specific syntax |
||
498 | case 'notregexp': return ['op' => 'NOT REGEXP', 'param' => $ruleInput]; // MySQL-specific syntax |
||
499 | case 'true': return ['op' => 'IS NOT NULL', 'param' => null]; |
||
500 | case 'false': return ['op' => 'IS NULL', 'param' => null]; |
||
501 | default: return ['op' => $ruleOperator, 'param' => $ruleInput]; // all numerical operators fall here |
||
502 | } |
||
503 | } |
||
504 | |||
505 | /** |
||
506 | * Format SQL condition matching the given advanced search rule and SQL operator. |
||
507 | * Derived classes should override this to provide support for table-specific rules. |
||
508 | */ |
||
509 | protected function advFormatSqlCondition(string $rule, string $sqlOp) : string { |
||
521 | } |
||
522 | } |
||
523 | |||
524 | /** |
||
525 | * Find an entity which has the same identity as the supplied entity. |
||
526 | * How the identity of the entity is defined, depends on the derived concrete class. |
||
527 | * @phpstan-param EntityType $entity |
||
528 | * @phpstan-return EntityType |
||
529 | */ |
||
530 | abstract protected function findUniqueEntity(Entity $entity) : Entity; |
||
531 | } |
||
532 |