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 |
||
14 | class PageRepository |
||
15 | { |
||
16 | /** |
||
17 | * Database table name that this repository maintains. |
||
18 | * |
||
19 | * @var string |
||
20 | */ |
||
21 | const TABLE = 'page'; |
||
22 | |||
23 | /** |
||
24 | * @var Connection |
||
25 | */ |
||
26 | private $connection; |
||
27 | |||
28 | /** |
||
29 | * PageRepository constructor. |
||
30 | * |
||
31 | * @param Connection $connection |
||
32 | */ |
||
33 | public function __construct(Connection $connection) |
||
37 | |||
38 | /** |
||
39 | * Fetches a page by slug. |
||
40 | * |
||
41 | * @param array $where |
||
42 | * |
||
43 | * @return null|PageEntity |
||
44 | */ |
||
45 | public function fetchOneBy(array $where = []) |
||
69 | |||
70 | /** |
||
71 | * Creates a page in the database. |
||
72 | * |
||
73 | * @param PageEntity $entity |
||
74 | * |
||
75 | * @return PageEntity |
||
76 | * |
||
77 | * @throws RecordAlreadyExistsException |
||
78 | */ |
||
79 | public function create(PageEntity $entity) |
||
96 | |||
97 | /** |
||
98 | * Update a page in the database. |
||
99 | * |
||
100 | * @param PageEntity $entity |
||
101 | * |
||
102 | * @return PageEntity |
||
103 | * |
||
104 | * @throws RecordNotPersistedException |
||
105 | */ |
||
106 | View Code Duplication | public function update(PageEntity $entity) |
|
124 | |||
125 | /** |
||
126 | * Removes a page from the database. |
||
127 | * |
||
128 | * @param PageEntity $entity |
||
129 | * |
||
130 | * @return PageEntity |
||
131 | * |
||
132 | * @throws RecordNotPersistedException |
||
133 | */ |
||
134 | View Code Duplication | public function remove(PageEntity $entity) |
|
152 | |||
153 | /** |
||
154 | * Maps the given entity to the database array. |
||
155 | * |
||
156 | * @param PageEntity $entity |
||
157 | * |
||
158 | * @return array |
||
159 | */ |
||
160 | View Code Duplication | public function getDatabaseArrayFromEntity(PageEntity $entity) |
|
172 | |||
173 | /** |
||
174 | * Prepares database array from properties. |
||
175 | * |
||
176 | * @param array $data |
||
177 | * |
||
178 | * @return PageEntity |
||
179 | */ |
||
180 | View Code Duplication | public function getEntityFromDatabaseArray(array $data) |
|
193 | } |
||
194 |
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.