Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 30 | class CardMapper extends DeckMapper implements IPermissionMapper { |
||
| 31 | |||
| 32 | private $labelMapper; |
||
| 33 | |||
| 34 | public function __construct(IDBConnection $db, LabelMapper $labelMapper) { |
||
| 35 | parent::__construct($db, 'deck_cards', '\OCA\Deck\Db\Card'); |
||
| 36 | $this->labelMapper = $labelMapper; |
||
| 37 | } |
||
| 38 | |||
| 39 | public function insert(Entity $entity) { |
||
| 44 | |||
| 45 | public function update(Entity $entity) { |
||
| 49 | |||
| 50 | /** |
||
| 51 | * @param $id |
||
| 52 | * @return RelationalEntity if not found |
||
| 53 | */ |
||
| 54 | public function find($id) { |
||
| 55 | $sql = 'SELECT * FROM `*PREFIX*deck_cards` ' . |
||
| 56 | 'WHERE `id` = ?'; |
||
| 57 | $card = $this->findEntity($sql, [$id]); |
||
| 58 | $labels = $this->labelMapper->findAssignedLabelsForCard($card->id); |
||
| 59 | $card->setLabels($labels); |
||
| 60 | return $card; |
||
| 61 | } |
||
| 62 | |||
| 63 | public function findAll($stackId, $limit = null, $offset = null) { |
||
| 64 | $sql = 'SELECT * FROM `*PREFIX*deck_cards` |
||
| 65 | WHERE `stack_id` = ? AND NOT archived ORDER BY `order`'; |
||
| 66 | $entities = $this->findEntities($sql, [$stackId], $limit, $offset); |
||
| 67 | return $entities; |
||
| 68 | } |
||
| 69 | |||
| 70 | public function findAllArchived($stackId, $limit = null, $offset = null) { |
||
| 75 | |||
| 76 | public function findAllByStack($stackId, $limit = null, $offset = null) { |
||
| 82 | |||
| 83 | public function delete(Entity $entity) { |
||
| 84 | // delete assigned labels |
||
| 85 | $this->labelMapper->deleteLabelAssignmentsForCard($entity->getId()); |
||
| 86 | // delete card |
||
| 87 | return parent::delete($entity); |
||
| 88 | } |
||
| 89 | |||
| 90 | public function deleteByStack($stackId) { |
||
| 97 | |||
| 98 | View Code Duplication | public function assignLabel($card, $label) { |
|
| 105 | |||
| 106 | View Code Duplication | public function removeLabel($card, $label) { |
|
| 113 | |||
| 114 | View Code Duplication | public function isOwner($userId, $cardId) { |
|
| 120 | |||
| 121 | public function findBoardId($cardId) { |
||
| 127 | |||
| 128 | |||
| 129 | } |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.